在C ++中将getline()与文件输入一起使用 [英] Using getline() with file input in C++

查看:106
本文介绍了在C ++中将getline()与文件输入一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

I tried using the getline function, as follows:

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函数在获得名称后停止,然后用某种重新启动"的方式检索该数字?无需操纵输入文件,那是?

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?

推荐答案

,顾名思义,读取整行,或者至少直到可以指定分隔符为止.

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", getlinedoes not match your need.

但是您可以执行以下操作:

But you can do something like:

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

这篇关于在C ++中将getline()与文件输入一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆