1

代码如下:

编码:

#include <iostream>
#include <fstream>

using namespace std;

int main(void)
{
    int id;
    char name[50];
    ifstream myfile("savingaccount.txt");  //open the file
    myfile >> id;

    myfile.getline(name , 255 , '\n');   //read name **second line of the file
    cout << id ;
    cout << "\n" << name << endl; //Error part : only print out partial name 
    return 0;
}

文件内容:

1800567
Ho Rui Jang
21 马来西亚
女性 012-4998192 20 , Lorong 13 , Taman Patani Janam Melaka Sungai Dulong





问题 :

1.)我希望getline将名称读入char数组名称然后我可以打印出名称,事情不是得到全名,我只得到部分名称,为什么会发生这种情况?

谢谢!

4

1 回答 1

2

问题是myfile >> id不使用\n第一行末尾的换行符 ( )。因此,当您调用getline它时,它将从 ID 的末尾读取到该行的末尾,您将得到一个空字符串。如果您再次调用getline它实际上将返回名称。

std::string name; // By using std::getline() you can use std::string
                  // instead of a char array

myfile >> id;
std::getline(myfile, name); // this one will be empty
std::getline(myfile, name); // this one will contain the name

我的建议是只使用std::getline所有行,如果一行包含一个数字,您可以使用std::stoi(如果您的编译器支持 C++11)或boost::lexical_cast.

于 2012-09-03T16:59:54.507 回答