【问题标题】:endl doesn't seem to executeendl 似乎没有执行
【发布时间】:2017-06-29 06:54:07
【问题描述】:

我已经阅读并重新阅读了代码,但我无法找到一个合乎逻辑的结论,说明为什么在运行时,在开始时间和结束时间之间没有创建换行符。积极和消极的建议都值得赞赏。

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main() {
    //start time and end time of shift
    vector <int> vstart;
    vector <int> vend;
    vector <string> days_of_week = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
    int start, end;
    while (cin >> start) {
        vstart.push_back(start);
    }
    while (cin >> end) {
        vend.push_back(end);
    }

    for (string d : days_of_week) {
        cout << d << "\t";
    }
    cout << endl << "---------------------------------------------------------\n";
    for (int s : vstart) {
        cout << s << "\t";
    }
    cout << endl;
    for (int e : vend) {
        cout << e << "\t";
    }
    cout << endl;
}    

【问题讨论】:

  • 对于一些指定的输入,你能告诉我们预期的和实际的输出吗?
  • 如果你想避免多余的复制操作,你应该使用for(const string&amp; d: days_of_week)
  • 输出应列出以 days_of_week 定义的星期几,由制表符分隔,后跟破折号屏障,然后是换行符,每个班次的开始时间,后跟换行符,每个班次的结束时间转变
  • 我很确定你没有end 次,第一个while 将所有内容放入vstart;您可以使用调试器轻松验证。您的输入看起来如何?
  • 另外,请显示(通过编辑问题)输入和输出。从终端复制粘贴它。请花一些时间到read about how to ask good questions。也请阅读 Eric Lippert 的 How to debug small programs

标签: c++ vector newline


【解决方案1】:

让我们看看这部分代码。

while (cin >> start) {
    vstart.push_back(start);
}
while (cin >> end) {
    vend.push_back(end);
}

在第一个循环中,您读取值直到cin&gt;&gt;start 到达文件结束字节,或者以不同的方式失败。但是您并没有清除该失败状态。 您必须调用 cin.clear(); 才能在第二个循环中读取新输入。

while (cin >> start) {
    vstart.push_back(start);
}
cin.clear();
while (cin >> end) {
    vend.push_back(end);
}

延伸阅读:Why would we call cin.clear() and cin.ignore() after reading input?

【讨论】:

    【解决方案2】:

    只要能够成功提取 int 值,就会执行此 while 循环。它在读完 7 个数字后不知道停下来,将您的所有输入都放入 vstart

    while (cin >> start) {
        vstart.push_back(start);
    }
    

    我认为您想要这样的for 循环,其中包含在读取 7 个值后停止的逻辑。

    for (int i = 0; (i < 7) && (cin >> start); ++i) {
        vstart.push_back(start);
    }
    

    【讨论】:

      猜你喜欢
      • 2022-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多