我遇到了从文件中读取字符串然后从文件读取双重内容的问题。我的教授建议我在每个输入行之后放一个特殊的getline,但它没有用,我推断这是程序的问题。是否有更简单的方式来接受双打?
输入文件的示例是:
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++;
}
答案 0 :(得分:2)
编辑:更新以回应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
答案 1 :(得分:0)
我认为Rob Adams的回复在解析多个记录时有一个小错误。首次提取d2
后,示例输入流将包含\nBen Stein\n989898\n100000000\n1
,因此下一次调用std::getline()
将提取空字符串而不是Ben Stein
。因此,似乎有必要在每个while循环迭代结束时使用空字符串。
我认为以下代码示例提供了一个修复:
#include <iostream>
#include <sstream>
int main(int argc, char** argv) {
using std::stringstream;
stringstream infile(stringstream::in | stringstream::out);
infile << "John Smith\n";
infile << "019283729102380\n";
infile << "300.00\n";
infile << "2000\n";
infile << "Andrew Lopez\n";
infile << "293481012100121\n";
infile << "400.00\n";
infile << "1500.00\n";
std::string account_name;
std::string account_number;
double current_balance;
double credit_limit;
int count = 0;
while (std::getline(infile, account_name) &&
std::getline(infile, account_number) >> current_balance >>
credit_limit) {
std::cout << account_name << std::endl;
std::cout << account_number << std::endl;
std::cout << current_balance << std::endl;
std::cout << credit_limit << std::endl;
/*
accname[count] = account_name;
accnum[count] = account_number;
currball[count] = current_balance;
credlim[count] = credit_limit;
*/
count++;
// Consume the leading newline character, which seprates the credit limit
// from the next account name, when infile contains multiple records.
//
// For example, after consuming the record for John Smith, the stream will
// contain: "\nAndrew Lopez\n293481012100121\n400.00\n1500.00\n". If you
// don't consume the leading newline character, calling std::getline() to
// parse the next account name will extract an empty string.
std::string blank;
std::getline(infile, blank);
}
return 0;
}
答案 2 :(得分:0)
string str;
while(!infile.eof())
{
getline(infile, accname[count]);// you do not need '\n' it will always read to
// end of the line
getline(infile, accnum[count]);
getline(infile, str);
currbal[count] = atof(str.c_str());
getline(infile, str);
credlim[count] = atof(str.c_str());
count++;
}
\*
for the file
John Smith
019283729102380
300.00
2000.00
Andrew Lopez
293481012100121
400.00
1500.00
*\