而循环跳过C字符串的cin.getline()

问题描述 投票:0回答:2

[我想使用while循环通过cin.getline()反复要求用户输入一行,并将输入存储为C字符串。

#include <iostream>
int main()
{
    const int N = 3;
    char arr[N + 1] = {};
    while (true)
    {
        std::cout << "Please enter " << N << " characters: ";
        std::cin.getline(arr, N + 1, '\n');
    }
}

如果用户键入aababc(然后按Enter),则while循环每次都会暂停,以允许下一行输入。但是,如果用户键入abcd,则while循环不会暂停,而只会重复输出“请输入3个字符:”。为什么?无论输入的时间长短如何如何让它每次都暂停?我曾尝试过cin.ignore,但我没有使它起作用。

c++ cin getline c-strings
2个回答
0
投票

根据documentation,第二个参数N + 1必须包含'\0'空终止符。因此,abcd输入不是有效输入,因为getline()需要5的大小来存储字符串以及'\0'


-1
投票

尝试以下操作:

std::string line;
while (std::getline(std::cin, line)) {
    std::string first_n = line.substr(0, N);
}
© www.soinside.com 2019 - 2024. All rights reserved.