带有结构的 C++ getline()

标签 c++ struct getline

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/

相关文章:

C - 我可以从 char * 创建一个 const char * 变量吗?

c++ - 无意中使用 = 而不是 ==

c - 如何自动向结构中的字节添加填充以修复 C 中的寄存器对齐?

结构编译器错误 vector 的 C++ 迭代器

c++ - 为什么C++中同时存在struct和class?

c - getline()/strsep() 组合导致段错误

c++ - 将变量与 C++ 中的数据类型进行比较

c++ - 为什么结果输出是整数即使结果被定义为 float ?

c++ - 如何忽略C++中的某些输入行?

c++ - 实现 "Reload"函数