cin.get & cin.getline doesn't work
May 20, 2011 at 12:25am UTC
can any1 tell me why all cin.get and cin.getline in this code doesn't work????
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
#include<iostream>
#include<istream>
#include<fstream>
#include<string>
using namespace std;
void write()
{
char address[20];
char stmt[100];
ofstream myfile;
cout<<"enter the address of the file you want to read: \n" ;
cin.get (address,20);
myfile.open(address);
cout<<"enter your statment\n" ;
cin>>skipws;
cin.getline (stmt,100);
myfile<<stmt;
return ;
}
void modify()
{
char address[20];
ofstream myfile;
cout<<"enter the address of the file you want to read\n" ;
cin.get(address,20);
myfile.open(address,ios::app);
myfile<<"writing again\n" ;
myfile<<"Ragnarok\n" ;
return ;
}
void read()
{
string address;
ifstream myfile;
cout<<"enter the address of the file you want to read\n" ;
getline(cin, address);
myfile.open (address.c_str(), ios::app);
const int line_length=100;
char str[line_length];
while (myfile.getline(str,line_length))
{
cout<<"read from file" <<str<<endl;
}
return ;
}
int main()
{
int x;
cout<<"hello user\n" ;
cout<<"press 1 to write\t" <<"press 2 to modify\t" <<"press 3 to read\t\n" ;
cin>>x;
cout<<endl;
switch (x)
{
case 1:
write();
break ;
case 2:
modify();
break ;
case 3:
read();
break ;
default :cout<<"wrong choice\n" ;
break ;
}
}
May 20, 2011 at 1:04am UTC
Your problem is line 51: cin>>x;
This leaves junk in the input buffer; you'll have to deal with it somehow or use getline() instead and convert it to a number yourself.
Topic archived. No new replies allowed.