ifstream在文件中获取错误的字符串

ifstream get the wrong string inside a file

本文关键字:取错误 字符串 获取 文件 ifstream      更新时间:2023-10-16

代码如下:

代码:

#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
何瑞章
21
女性
马来西亚语
012-4998192
20,罗荣13,Taman Patani Janam
马六甲
Sungai Dulong

问题:

1.)我希望getline将名称读取到char数组名称中,然后我可以打印出名称,问题是我没有得到全名,我只得到了名称的一部分,为什么会发生这种情况?

谢谢!

问题是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进行转换。