【问题标题】:For-Loop Skipping getline C++ [duplicate]For-Loop跳过getline C ++ [重复]
【发布时间】:2015-09-30 20:32:20
【问题描述】:

我遇到了一个问题,我的 for 循环跳过了 getline 函数。如果我用 std::cin 替换它,那么它可以工作,所以我认为这与我在 getline 中输入的内容有关。

这是我的代码。

void setLocations(int amount) {
    locations = new std::string[amount];
    locations[0] = startingLocation;

    // starts at 1 because we want to skip first index. The amount is set at 2 by default, so the loop should iterate at least once.
    for (int x = 1; x < amount; x++)
        std::getline(std::cin, locations[x]);    
}

【问题讨论】:

标签: c++ for-loop getline


【解决方案1】:

可能你在调用 'setLocations' 函数之前使用了 'std::cin>>someVar',它不会消耗换行符。要解决,请在“for”循环之前使用此代码段

std::cin.ignore(1, '\n');

【讨论】:

  • 我收到一个错误,提示我在使用 cin.ignore(1, "\n"); 时无法初始化 int_type 的参数;
  • @Xari,抱歉我的错误使用 '\n' 而不是 "\n"。
猜你喜欢
  • 2021-11-24
  • 1970-01-01
  • 1970-01-01
  • 2021-11-26
  • 1970-01-01
  • 2017-02-13
  • 2016-02-05
相关资源
最近更新 更多