【问题标题】:Program skipping second while loop (reading into int and string vectors respectively using cin)程序跳过第二个 while 循环(分别使用 cin 读入 int 和 string 向量)
【发布时间】:2023-04-02 03:10:01
【问题描述】:

我不明白为什么将输入读入向量的第二个 while 循环没有迭代。我尝试使用getchar() 在第一部分(从输入然后输出读取 int 向量)和第二部分(从输入读取字符串向量,然后输出)。代码如下:

#include <iostream>
#include <string>
#include <cctype>
#include <vector>
using std::cin; using std::cout; using std::endl; using std::string; using std::cerr; using std::vector;

int main() {
    vector<int> numbs; // empty vector
    int inp_num;
    while (cin >> inp_num)
        numbs.push_back(inp_num);

    for (const auto& k : numbs)
        cout << k << " ";
    cout << endl;

    //part 2
    vector<string> text; // empty vector
    string inp_text;
    while (cin >> inp_text)
        text.push_back(inp_text);

    for (const auto& j : text)
        cout << j << " ";
    cout << endl;

    system("pause>0");
    return 0;
}

【问题讨论】:

  • 你期待输入结束吗?在执行cin &gt;&gt; inp_num时输入非数字?
  • while (cin &gt;&gt; inp_num) 一直执行到流错误或失败(包括 eof)。一旦发生这种情况,每次格式化的提取,包括成功的提取都将继续失败,直到流错误状态被重置。

标签: c++ vector


【解决方案1】:

您的问题是std::cin 缓冲区已经包含EOF 或其他会导致跳过第二个循环的输入。试试这个:

std::cin.clear();
std::cin.ignore();

就在这部分代码之前

//part 2
vector<string> text; // empty vector
string inp_text;
while (cin >> inp_text)
    text.push_back(inp_text);

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2016-10-22
  • 2019-08-11
  • 2015-11-05
  • 2013-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多