gpt4 book ai didi

带有结构的 C++ getline()

转载 作者:行者123 更新时间:2023-11-28 03:32:20 24 4
gpt4 key购买 nike

struct car
{
string name;
int year;
};

int main() {
int noOfCars;
cout<<"enter no_ of cars : ";
cin>>noOfCars;
car* cars = new car[noOfCars];
for(int i=0;i<noOfCars;i++)
{
cout<<"Car #"<<i<<endl;
cout<<"Name : ";
getline(cin,(cars[i].name)); //here is the problem
cout<<"\n year : ";
cin>>cars[i].year;
cout<<endl;
}
}

将整行作为字符串输入到 strcut 中的名称时出现问题,甚至不接受任何内容并直接继续获取年份 ... :S ???

它适用于 cin,但我想要整行!它适用于全局定义的字符串,但不适用于结构中的 this

最佳答案

getline 之后插入 cin.ignore( 1000, '\n' );

#include<string>
#include<iostream>
using namespace std;

struct car
{
string name;
int year;
};

int main() {
int noOfCars;
cout<<"enter no_ of cars : ";
cin>>noOfCars;
car* cars = new car[noOfCars];
for(int i=0;i<noOfCars;i++)
{
cin.clear();


cout<<"Car #"<<i<<endl;
cout<<"Name : ";
getline(cin,(cars[i].name)); //here is the problem

cin.ignore( 1000, '\n' );

cout<<"\n year : ";
cin>>cars[i].year;
cout<<endl;

}
return 0;
}

关于带有结构的 C++ getline(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12145930/

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