如何在C ++中读取由要读取的字符数定义的文件段?

时间:2012-12-19 13:15:29

标签: c++ ifstream

我在从文件中读取特定数据时遇到一些问题。该文件在第一行和第二行有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;
}

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

2 个答案:

答案 0 :(得分: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个字符长的信息(我假设您正在读取基于行的文件格式)。如果重要,您可以添加额外的检查。

答案 1 :(得分: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;
}