I’m trying to get input from user and give output until s/he presses ‘n’. It doesn’t seem to work. Is problem in scanf or cin.get? When I press y it just takes “tekrar” as an input, thus gives “y” as output and goes into a loop. Also, doesn’t stop when i give n as tekrar input.
char cevap[300]="";
char tekrar='y';
while (tekrar!='n')
{
cin.get(cevap,300);
cout<<cevap<<endl;
cout<<"Again? (y/n)";
scanf("%c",&tekrar);
}
output:
Hello
Again? (y/n)
y
Again? (y/n)
y
Again? (y/n)
n
Again? (y/n)
n
...
Mixing the various input methods on
istream(get,getline,operator>>) can be fraught with peril if you’re not aware of which methods leave the delimiter character in the stream and which don’t, and handle them accordingly.In this case,
getwill read 300 characters of input or input up until the newline, whichever happens first. The newline will not be extracted, and so will remain in the stream. That means your call toscanf()will read the newline and stop, leaving theyornyou just typed in the stream.There are several ways to reorganize this code to make it do what it seems like you want. This is one way:
This uses
std::stringand the non-membergetlineto read input in such a way as to not require you to be limited to 300 characters (not strictly speaking related to the question, but good practice usually).getlineconsumes and discards the delimiter, butget, used to read the continuation input, doesn’t, so we discard it manually viaignore.