2

我在从文件中读取特定数据时遇到了一些问题。该文件的第一行和第二行有 80 个字符,第三行有未知数量的字符。以下是我的代码:

int main(){
    ifstream myfile;
    char strings[80];
    myfile.open("test.txt");
    /*reads first line of file into strings*/
    cout << "Name: " << strings << endl;
    /*reads second line of file into strings*/
    cout << "Address: " << strings << endl;
    /*reads third line of file into strings*/
    cout << "Handphone: " << strings << endl;
}

我如何执行评论中的操作?

4

2 回答 2

3

char strings[80]只能容纳 79 个字符。让它char strings[81]。如果您使用std::string.

std::getline您可以使用该功能读取行。

#include <string>

std::string strings;

/*reads first line of file into strings*/
std::getline( myfile, strings );

/*reads second line of file into strings*/
std::getline( myfile, strings );

/*reads third line of file into strings*/
std::getline( myfile, strings );

上面的代码忽略了第一行和第二行长度为 80 个字符的信息(我假设您正在阅读基于行的文件格式)。如果它很重要,您可以为此添加额外的检查。

于 2012-12-19T13:21:57.360 回答
1

在您的情况下,使用字符串而不是 char[] 会更合适。

#include <string>
using namespace std;

int main(){
    ifstream myfile;
    //char strings[80];
    string strings;
    myfile.open("test.txt");

    /*reads first line of file into strings*/
    getline(myfile, strings);
    cout << "Name: " << strings << endl;
    /*reads second line of file into strings*/
    getline(myfile, strings);
    cout << "Address: " << strings << endl;
    /*reads third line of file into strings*/
    getline(myfile, strings);
    cout << "Handphone: " << strings << endl;
}
于 2012-12-19T13:43:08.040 回答