For循环跳过getline C++
For-Loop Skipping getline C++
我遇到了一个问题,我的 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]);
}
可能是您在 'setLocations' 函数调用之前使用了 'std::cin>>someVar',它不消耗换行符。要解决,请在 'for' 循环
之前使用此代码段
std::cin.ignore(1, '\n');
我遇到了一个问题,我的 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]);
}
可能是您在 'setLocations' 函数调用之前使用了 'std::cin>>someVar',它不消耗换行符。要解决,请在 'for' 循环
之前使用此代码段std::cin.ignore(1, '\n');