1
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 中的名称时出现问题,甚至不带任何东西并直接继续 ge 年份...:S ???

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

4

4 回答 4

3

正如克里斯所说,这已经解释了很多次。

问题出在您之前的输入调用中

cin>>noOfCars;

这读取一个数字,即它读取数字,它不读取换行符。您可能会键入一个换行符,但这并不意味着它会被读取。事实上,换行符会一直保留到您下次阅读时,即您的getline电话。因此getline,当您读取汽车数量时,您的第一个电话会读取剩余的换行符。

新手会犯这个错误并不让我感到惊讶,但这确实表明您应该在提问之前花一些时间研究您的问题。这个问题已经被问过数百次了。

于 2012-08-27T16:50:05.073 回答
2

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

#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;
}
于 2012-08-27T17:12:07.667 回答
0

The problem is that cin>>noOfCars leaves the newline generated by the Enter key in the input queue. The getline(cin,(cars[i].name)) is simply reading that newline character and assigns a null string to the car[i].name array. And since at the end of your loop cin>>cars[i].year does the same thing over and over, getline(cin,(cars[i].name)) is always reading a newline character before it lets you input anything.

To fix this you just need to discard the newlines character after cin reads noOfCars and cars[i].year, which can be cleanly done by concatenating a cin.get() after your cins like this:

cout<<"enter no_ of cars : ";    
(cin>>noOfCars).get();            //here is the solution
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).get();   //here is the solution 
    cout<<endl;
}
于 2016-05-05T18:25:13.480 回答
-1

Try cin.getline(Cars[i].name,streamsize); 其中streamsize 是字符串的最大大小。我认为这是最简单的形式。

于 2012-08-27T16:57:57.717 回答