使用getline()时while和if之间的差异



我有一个.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;
}

我正在使用";转移";bool变量作为一种从文件中读取一行,然后从第二个文件中读取另一行的方法。第一个.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

如果你们需要澄清我的问题,请告诉我。如有任何帮助,我们将不胜感激。谢谢

while是一个循环语句,因此执行是循环的。

让我们一步一步来看看会发生什么:

transfer = true; // (1)
while (getline(read_amount, line) && transfer == true) // (2)
{
cout << "$" << line << endl; // (3)
transfer = false; // (4)
}
  1. transfer在第(1(行设置为true
  2. 在第(2(行向line读取某些内容
  3. 进入循环,因为第(2(行的transfertrue
  4. 第(3(行打印了一些内容
  5. 在第(4(行将transfer设置为false
  6. line在第(2(行读取了一些内容
  7. 断开循环,因为第(2(行的transferfalse

在这一步中,读取要完成两次,它将消耗输入中的某些内容。另一方面,使用if,执行不循环,读取只进行一次。这会有所不同。

最新更新