在 C++ 中将 getline() 与文件输入一起使用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20739453/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using getline() with file input in C++
提问by Ghost Repeater
I am trying to do a simple beginner's task in C++. I have a text file containing the line "John Smith 31". That's it. I want to read in this data using an ifstream variable. But I want to read the name "John Smith" into one string variable, and then the number "31" into a separate int variable.
我正在尝试用 C++ 做一个简单的初学者任务。我有一个包含“John Smith 31”行的文本文件。就是这样。我想使用 ifstream 变量读入此数据。但我想将名字“John Smith”读入一个字符串变量,然后将数字“31”读入一个单独的 int 变量。
I tried using the getline function, as follows:
我尝试使用 getline 函数,如下所示:
ifstream inFile;
string name;
int age;
inFile.open("file.txt");
getline(inFile, name);
inFile >> age;
cout << name << endl;
cout << age << endl;
inFile.close();
The problem with this is that it outputs the entire line "John Smith 31". Is there a way I can tell the getline function to stop after it has gotten the name and then kind of "restart" to retrieve the number? Without manipulating the input file, that is?
问题在于它输出整行“John Smith 31”。有没有办法告诉 getline 函数在获得名称后停止,然后“重新启动”以检索号码?不操作输入文件,那是什么?
回答by Johan
getline
, as it name states, read a whole line, or at least till a delimiter that can be specified.
getline
,顾名思义,读取整行,或者至少读取到可以指定的分隔符。
So the answer is "no", getline
does not match your need.
所以答案是“不”,getline
不符合您的需要。
But you can do something like:
但是您可以执行以下操作:
inFile >> first_name >> last_name >> age;
name = first_name + " " + last_name;
回答by Zeeshan
you should do as:
你应该这样做:
getline(name, sizeofname, '\n');
strtok(name, " ");
This will give you the "joht" in namethen to get next token,
这将为您提供名称中的“joht”, 然后获取下一个令牌,
temp = strtok(NULL, " ");
tempwill get "smith" in it. then you should use string concatination to append the temp at end of name. as:
temp将在其中添加“史密斯”。那么您应该使用字符串连接在名称末尾附加临时值。作为:
strcat(name, temp);
(you may also append space first, to obtain a space in between).
(您也可以先添加空格,以获得中间的空格)。
回答by SliceSort
ifstream inFile;
string name, temp;
int age;
inFile.open("file.txt");
getline(inFile, name, ' '); // use ' ' as separator, default is '/n'. 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();