【发布时间】:2021-01-24 19:26:13
【问题描述】:
我有一个 .cpp 文件,它读取两个 .txt 文件并将它们输出到屏幕上。 代码如下:
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
using namespace std;
class check
{
public:
void display();
ifstream read_number, read_amount;
};
void check::display()
{
read_number.open("number.txt");
read_amount.open("amount.txt");
if (read_number.is_open() && read_amount.is_open())
{
string line;
bool transfer = false;
while (getline(read_number, line) && transfer == false)
{
cout << line << "\t";
transfer = true;
if (getline(read_amount, line) && transfer == true)
{
cout << "$" << line << endl;
transfer = false;
}
}
cout << endl;
}
else cout << "Unable to open one of the two files." << endl;
}
int main()
{
check obj;
obj.display();
return 0;
}
我使用“传输”布尔变量作为从文件中读取一行然后从第二个文件中读取另一行的一种方式。 第一个 .txt 文件只有这些数字,没有别的:
03
32
26
第二个 .txt 文件有这些数字:
50.30
15.26
20.36
上面的代码按预期工作。运行时会产生如下结果:
03 $50.30 // first value is from file 1, second value from file 2.
32 $15.26
26 $20.36
但是,我的问题是,为什么以下更改会导致输出中省略最后一个值 (20.36)?
改变:
while (getline(read_amount, line) && transfer == true)
{
cout << "$" << line << endl;
transfer = false;
}
变化产生的输出:
03 $50.30 // first value is from file 1, second value from file 2.
32 $15.26
26
如果你们需要对我的问题进行任何澄清,请告诉我。任何帮助,将不胜感激。谢谢!
【问题讨论】:
-
“如果你们需要任何澄清,请告诉我” 是的,我们需要minimal reproducible example,这是在这里询问时的要求。
-
无关:
if (read_number.is_open() && read_amount.is_open())可以写成if(read_number && read_amount) -
仅供参考,
while (transfer && getline(read_amount, line))将返回您预期的行为。 -
@πάνταῥεῖ 抱歉,这是可重现的代码。
-
感谢您的所有反馈,Ted 和 Craig!
标签: c++ if-statement while-loop getline