我试图在一个文件中打印3行,但最终发生的是打印所有3个点中的1行,打印所有3个点中的第2行,然后,你猜对了,与第3名相同。我想让它按一下按钮打印出所有3行。
ifstream read_file;
string fname, name;
cout << "Type the complete address of the file you would like to open.\n";
cin >> fname;
system("cls");
read_file.open(fname.c_str());
while(getline(read_file, fname))
{
if (fname == "")continue;
cout << "You had "<< fname << " health left\n";
cout << "You delt " << fname << " damage\n";
cout << "There were " << fname << " enemies left\n";
system("pause");
}
read_file.close();
system("pause");
答案 0 :(得分:4)
查看您的代码
while(getline(read_file, fname))
{
if (fname == "")
continue;
cout << "You had "<< fname << " health left\n";
cout << "You delt " << fname << " damage\n";
cout << "There were " << fname << " enemies left\n";
system("pause");
}
很明显,你只读了一行,并打印了三次 - 你在这些输出之间没有做任何事情fname
。
我建议您停止重复使用同一个变量用于多种目的,这是许多错误的来源 (以下假设没有空行。)
string health;
string damage;
string enemies;
while(getline(read_file, health) && getline(read_file, damage) && getline(read_file, enemies))
{
cout << "You had "<< health << " health left\n";
cout << "You delt " << damage << " damage\n";
cout << "There were " << enemies << " enemies left\n";
}
如果文件中有空行,请考虑编写自己的跳过空行的getnonemptyline
函数。
答案 1 :(得分:0)
就像molbdnilo所说,你只是从文件中读取一行,然后尝试用它做三件事。如果你想继续重复使用相同的(奇怪名称)变量,你可以像
那样做while(getline(read_file, fname)){
if (fname == "")continue;
cout << "You had "<< fname << " health left\n";
}
while(getline(read_file, fname)){
if (fname == "")continue;
cout << "You delt " << fname << " damage\n";
}
while(getline(read_file, fname)){
if (fname == "")continue;
cout << "There were " << fname << " enemies left\n";
}
system("pause");