gpt4 book ai didi

c++ cin 输入不起作用?

转载 作者:太空狗 更新时间:2023-10-29 19:54:35 25 4
gpt4 key购买 nike

#include <iostream>
#include <string>

struct Car{
std::string model;
unsigned int year;
};

int main(){
using namespace std;

int carNum;
cout << "How many cars do you wish you catalog? ";
cin >> carNum;
Car * cars = new Car[carNum];

for (int i=0;i<carNum;i++){
cout << "Car #" << i << endl;
cout << "Please enter the make: ";
getline(cin, cars[i].model);

cout << "Please enter the year made: ";
cars[i].year = cin.get();
}

cout << "Here's your collection" << endl;

for (int i=0;i<carNum;i++){
cout << cars[i].model << " " << cars[i].year << endl;
}

delete [] cars;

return 0;
}

当我执行程序时,getline(cin, car[i].model) 就被跳过了。这是为什么?

像这样:

Car #2
Please enter the make: Please enter the year made:

最佳答案

原因很简单。

当你执行 cin >> whatever 时,会留下一个 \n(它是在你按下 Enter 时添加的)。默认情况下,getline 会一直读取到下一个 \n,因此下一次读取只会读取一个空字符串。

解决方案是丢弃那个\n。您可以通过以下方式做到这一点:

cin.ignore(numeric_limits<streamsize>::max(),'\n');

就在 cin >> carNum 之后。

不要忘记包含 limits 以便使用 numeric_limits

关于c++ cin 输入不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5877420/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com