C++帮助使用 ifstream 的 getline 函数
所以我正在编写一个程序来处理读入和写出文件。我使用 getline() 函数,因为文本文件中的某些行可能包含多个元素。到目前为止,我从来没有遇到过 getline 问题。这就是我得到的。
文本文件如下所示:
John Smith // Client name
1234 Hollow Lane, Chicago, IL // Address
123-45-6789 // SSN
Walmart // Employer
58000 // Income
2 // Number of accounts the client has
1111 // Account Number
2222 // Account Number
代码如下:
ifstream inFile("ClientInfo.txt");
if(inFile.fail())
{
cout << "Problem opening file.";
}
else
{
string name, address, ssn, employer;
double income;
int numOfAccount;
getline(inFile, name);
getline(inFile, address);
// I'll stop here because I know this is where it fails.
当我调试此代码时,我发现 name == "John",而不是 name == "John Smith",并且 Address == "Smith" 等等。我做错了什么吗?任何帮助将不胜感激。
So I am writing a program that deals with reading in and writing out to a file. I use the getline() function because some of the lines in the text file may contain multiple elements. I've never had a problem with getline until now. Here's what I got.
The text file looks like this:
John Smith // Client name
1234 Hollow Lane, Chicago, IL // Address
123-45-6789 // SSN
Walmart // Employer
58000 // Income
2 // Number of accounts the client has
1111 // Account Number
2222 // Account Number
And the code like this:
ifstream inFile("ClientInfo.txt");
if(inFile.fail())
{
cout << "Problem opening file.";
}
else
{
string name, address, ssn, employer;
double income;
int numOfAccount;
getline(inFile, name);
getline(inFile, address);
// I'll stop here because I know this is where it fails.
When I debugged this code, I found that name == "John", instead of name == "John Smith", and Address == "Smith" and so on. Am I doing something wrong. Any help would be much appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您显示的代码应该适用于该文件。所以一定有什么东西和你想象的不一样。最可能的罪魁祸首是:
inFile >>> name
您认为它使用了getline(inFile,name)
也许您更改了某些内容并忘记保存或重新编译,或者您正在读取与您想象的不同的文件。
顺便说一句,从您的变量声明来看,您可能计划将
getline()
调用与提取运算符调用(如inFile >>> )混合使用。收入。混合这些需要小心,因为提取运算符会留下
getline()
可能会读取的尾随空白。 此底部附近有更多信息。The code you show should work on that file. So something must be different than you think. The most likely culprits are:
inFile >> name
where you think it usesgetline(inFile,name)
Perhaps you changed something and forgot to save or recompile or you are reading a a different file than you think.
By the way, from your variable declarations it looks like you may be planning to mix
getline()
calls with extraction operator calls likeinFile >> income
. Mixing these requires care because the extraction operator leaves behind trailing whitespace thatgetline()
might then read. There's more information near the bottom of this.