简体   繁体   中英

Why getline not accepting input

From top of the code is working but surprisingly the last cin.get(con) doesn't wait for input and terminate the program with accepting any input, why this is happening so, kindly guide me what is wrong with my code -

#include<iostream.h>
#include<conio.h>
#include <string.h>
struct country
{
char country[30];
char capital[30];
float income;
};

void main()
{
  country c[3];
  clrscr();
  for( int i=0; i<3 ; i++)
  {
    cout << "\n Country's name : ";
    cin.ignore();
    cin.getline(c[i].country, 30);

    cout << "\n Country's capital :";
    cin.getline(c[i].capital,30);

    cout << "\n Per capita income :";
    cin >> c[i].income;

  }

char ch = 'y';
char cap[30];
int flag = 0;
cin.ignore();
cout << "\n Enter Capital name : ";
cin.getline(cap, 30);

  for(int k=0; k<3 ; k++)
  {
     flag = 0;
     if(strcmp(c[k].capital,cap)==0)
     {
        flag = 1;
     }
     if(flag==1)
     {
        cout<< "\n" << c[k].country << "\t" << c[k].capital << "\t" << c[k].income << "\n\n" ;
     }
  }
char con[30];
cout << "\n Enter Country name : ";
cin.getline(con,30);
  for(int m=0; m<3 ; m++)
  {
     flag = 0;
     if(strcmp(c[m].country,con)==0)
     {
        flag = 1;
     }
     if(flag==1)
     {
        cout  << c[m].capital << "\t" << c[m].income << "\n" ;
     }
  }
}

Combining cin.operator<< and getline results in strange behavior. So, this code should be changed

cout << "\n Country's capital :";
cin.getline(c[i].capital,30);

cout << "\n Per capita income :";
cin >> c[i].income;

Possibly to

cout << "\n Country's capital :";
cin.getline(c[i].capital,30);

char buf[50]; //I don't know how long your floats are
cout << "\n Per capita income :";
cin.getline(buf);
c[i].income = atof(buf);  //#include <cstdlib>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM