【问题标题】:Using getline() with file input in C++在 C++ 中将 getline() 与文件输入一起使用
【发布时间】:2014-01-11 10:20:18
【问题描述】:

我正在尝试用 C++ 完成一个简单的初学者任务。我有一个包含该行的文本文件 “约翰史密斯 31”。而已。我想使用 ifstream 变量读取这些数据。但我想将名称“John Smith”读入一个字符串变量,然后将数字“31”读入一个单独的 int 变量。

我尝试使用getline函数,如下:

ifstream inFile;
string name;
int age;

inFile.open("file.txt");

getline(inFile, name); 
inFile >> age; 

cout << name << endl;
cout << age << endl;  

inFile.close();    

问题在于它会输出整行“John Smith 31”。有没有一种方法可以告诉 getline 函数在它获得名称后停止,然后“重新启动”来检索号码?不操纵输入文件,那是什么?

【问题讨论】:

  • 如果你不想读一行,不要打电话给getline。真的就是这么简单。

标签: c++ getline


【解决方案1】:

getline,顾名思义,读一整行,或至少读到可以指定的分隔符。

所以答案是“不”,getline不符合您的需要。

但你可以这样做:

inFile >> first_name >> last_name >> age;
name = first_name + " " + last_name;

【讨论】:

  • 我的意思是,如果它以这种方式工作。我在某处读到,我们需要将字符串指定为 std::string x;,以使用 + 进行连接。否则,编译器假定您正在尝试添加 char 指针。那是仪式吗?或者它只是按照提到的方式工作?只是想为我自己说清楚。谢谢
  • 如果您查看the list of overload of operator+() with a std::string,您会发现只要参数中的一个为std::string,它就会起作用。那里没有魔法 :) 但是如果你用 + 来调用 char* 它是行不通的。
【解决方案2】:
ifstream inFile;
string name, temp;
int age;

inFile.open("file.txt");

getline(inFile, name, ' '); // use ' ' as separator, default is '\n' (newline). Now name is "John".
getline(inFile, temp, ' '); // Now temp is "Smith"
name.append(1,' ');
name += temp;
inFile >> age; 

cout << name << endl;
cout << age << endl;  

inFile.close();    

【讨论】:

    【解决方案3】:

    你应该这样做:

    getline(name, sizeofname, '\n');
    strtok(name, " ");
    

    这将为您提供 name 中的“joht” 然后获取下一个令牌,

    temp = strtok(NULL, " ");
    

    temp 将在其中包含“smith”。那么你应该使用字符串连接将临时附加到名称的末尾。如:

    strcat(name, temp);
    

    (您也可以先追加空格,以获取中间的空格)。

    【讨论】:

    • strtok() 更像是一个 C 解决方案。向新用户介绍 STL 概念可能会更好
    【解决方案4】:

    您可以使用此代码从文件中使用 getline。 此代码将从文件中取出一整行。然后你可以使用 while 循环来遍历所有行 while (ins);

     ifstream ins(filename);
    string s;
    std::getline (ins,s);
    

    【讨论】:

    • 这似乎没有回答问题,尝试添加更多信息以正确回答问题
    猜你喜欢
    • 2012-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-08
    • 1970-01-01
    • 2014-04-04
    相关资源
    最近更新 更多