繁体   English   中英

在 C++ 中将 getline() 与文件输入一起使用

[英]Using getline() with file input in C++

我正在尝试用 C++ 做一个简单的初学者任务。 我有一个包含“John Smith 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 ,顾名思义,读取整行,或至少读取到可以指定的分隔符。

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

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

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

你应该这样做:

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

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

temp = strtok(NULL, " ");

temp将在其中添加“史密斯”。 那么您应该使用字符串连接在名称末尾附加临时值。 如:

strcat(name, temp);

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

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();    

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM