【问题标题】:ifstream get the wrong string inside a fileifstream 在文件中获取错误的字符串
【发布时间】:2012-09-03 16:43:18
【问题描述】:

代码如下:

代码:

#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 , Lorong 13 , Taman Patani Janam
马六甲
双溪独龙

问题:

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

谢谢!

【问题讨论】:

  • 是完全相同的代码吗?另外,它打印什么?也发布输出。

标签: c++ fstream


【解决方案1】:

问题是myfile &gt;&gt; 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来转换它。

【讨论】:

  • 此外,要解析更复杂的行,请将字符串传递给std::ostringstream 的构造函数,并根据需要运行提取器。
  • @PeteBecker 确实如此。根据输入格式,使用正则表达式也很方便。
  • 我尝试计算 myfile.tellg() "myfile >> id;"我得到的值是 16 ,为什么会这样?我认为第一行 1800567 应该有 7 位数字,在用“myfile >> id”读取它之后,流指针应该放在名称之前的位置,即 7 或 8但为什么是 16?
  • @caramel23 我不是 100% 确定,但它可能与您使用的编码有关。例如,如果您使用 UTF-16,每个字符将占用两个字节。 16 = 8 x 2。
猜你喜欢
  • 1970-01-01
  • 2012-02-08
  • 2021-02-23
  • 1970-01-01
  • 2011-09-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-03
相关资源
最近更新 更多