[我想使用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');
}
}
如果用户键入a
,ab
或abc
(然后按Enter),则while循环每次都会暂停,以允许下一行输入。但是,如果用户键入abcd
,则while循环不会暂停,而只会重复输出“请输入3个字符:”。为什么?无论输入的时间长短如何如何让它每次都暂停?我曾尝试过cin.ignore
,但我没有使它起作用。
根据documentation,第二个参数N + 1
必须包含'\0'
空终止符。因此,abcd
输入不是有效输入,因为getline()
需要5
的大小来存储字符串以及'\0'
。
尝试以下操作:
std::string line;
while (std::getline(std::cin, line)) {
std::string first_n = line.substr(0, N);
}