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



我正在尝试用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();    

这样做的问题是它输出整行"约翰史密斯 31"。有没有办法告诉getline函数在获得名称后停止,然后"重新启动"以检索数字?不操作输入文件,就是?

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

所以答案是否定的,getline不符合您的需求。

但是你可以做这样的事情:

inFile >> first_name >> last_name >> age;
name = first_name + " " + last_name;
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(name, sizeofname, 'n');
strtok(name, " ");

这会给你名字上的"joht"然后获取下一个令牌,

temp = strtok(NULL, " ");

临时将在其中得到"史密斯"。 然后,您应该使用字符串连接将 temp 附加到名称末尾。 作为:

strcat(name, temp);

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

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

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

最新更新