我在从文件中读取字符串然后从文件中读取 double 时遇到问题。我的教授建议我在每个输入行之后放置一个特殊的 getline,但它没有用,我推断这是程序的问题。有没有更简单的方法来接受 double ?
输入文件的例子是:
John Smith
019283729102380
300.00
2000.00
Andrew Lopez
293481012100121
400.00
1500.00
代码如下:
while(! infile.eof())
{
getline(infile,accname[count],'\n');
getline(infile, refuse, '\n');
getline(infile,accnum[count],'\n');
getline(infile, refuse, '\n');
infile>>currbal[count];
getline(infile, refuse, '\n');
infile>>credlim[count];
getline(infile, refuse, '\n');
count++;
}
最佳答案
编辑:根据 OP 的澄清进行了更新。
根据您提供的示例,这应该可行:
while(1) {
std::string s1;
if(!std::getline(infile, s1))
break;
std::string s2;
if(!std::getline(infile, s2))
break;
double d1, d2;
if(!(infile >> d1 >> d2))
break;
accname[count] = s1;
accnum[count] = s2;
currball[count] = d1;
credlim[count] = d2;
count++;
}
此代码适用于以下输入:
Adam Sandler
0112233
5 100
Ben Stein
989898
100000000
1
但它不适用于如下输入:
Adam Sandler
0112233
5 100
Ben Stein
989898
100000000
1
关于c++ - 阅读字符串和 double ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5783691/