Click here to Skip to main content
15,922,584 members
Please Sign up or sign in to vote.
4.00/5 (2 votes)
See more:
if i am writing the following code then at run time the code is not asking for the string and it takes only the value of number, why it is?

C++
#include<iostream.h>
#include<fstream.h>
#include<conio.h>

class x
{
      char ch[30];
      int num;
      public:
             void getdata()
             {
                  cout<<"Enter string";
                  cin.getline(ch,30);
                  cout<<"Enter a number :";
                  cin>>num;    
             }
};

int main()
{
    x o;
    int choice;
    cout<<"Enter your choice 1 for getdata and 2 to exit";
    cin>>choice;
    if(choice==1)
                 o.getdata();
    else
                 exit(0);
    getch();
    return 0;
}


[edit]Code block added, html encoded - OriginalGriff[/edit]
Posted
Updated 5-Apr-12 20:05pm
v3

This may be due to a '\n' left in the stream from some other part of your program. Flush the stream before using getline(). What chandanadhikari suggested is absolutely right. Try using cin.ignore() or cin.sync and cin.clear ,your problem will be solved.
C++
class x
{
      
	
        char ch[30];
        int num;
        public:
	
             void getdata()
             {
				 
	         cout<<"Enter string:\n";
                  cin.ignore(); 
		getline(cin,s);
                  cout<<"Enter a number :";
                  cin>>num;    
				  
             }
};
 
Share this answer
 
hi,
use cin.ignore() before cin.getline() and tell what happens .
also you can check if using, cin.clear() and cin.sync() after the number is entered helps.
 
Share this answer
 
check if using, cin.clear() and cin.sync() after the number is entered helps.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900