【问题标题】:Difference between while and if when using getline() [closed]使用getline()时while和if之间的区别[关闭]
【发布时间】: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() &amp;&amp; read_amount.is_open())可以写成if(read_number &amp;&amp; read_amount)
  • 仅供参考,while (transfer &amp;&amp; getline(read_amount, line)) 将返回您预期的行为。
  • @πάνταῥεῖ 抱歉,这是可重现的代码。
  • 感谢您的所有反馈,Ted 和 Craig!

标签: c++ if-statement while-loop getline


【解决方案1】:

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. 进入循环内部,因为transfer 在第 (2) 行是 true
  4. 在第 (3) 行打印了一些内容
  5. transfer 在第 (4) 行设置为 false
  6. 在第 (2) 行向 line 读取了一些内容
  7. 退出循环,因为transfer 在第 (2) 行是 false

在这一步中,读取完成了两次,它会从输入中消耗一些东西。 另一方面,使用if,执行不会循环,并且只读取一次。 这会有所作为。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-20
    • 1970-01-01
    • 2013-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-12
    相关资源
    最近更新 更多