platypus
platypus

Reputation: 706

cin.get in a while loop

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 
...  

Upvotes: 1

Views: 9420

Answers (2)

mfontanini
mfontanini

Reputation: 21910

Use cin operator>> to read from stdin, instead of scanf:

string cevap;
char tekrar='y';
while (tekrar!='n')
{
  getline(cin, cevap);
  cout<<cevap<<endl;
  cout<<"Again? (y/n)";
  cin >> tekrar;
  cin.get();
}

Edit: fixed the infinite loop. You should use std::string instead of a simple char array.

Upvotes: 3

user197015
user197015

Reputation:

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, get will 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 to scanf() will read the newline and stop, leaving the y or n you 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:

#include <iostream>
#include <string>

using namespace std;
int main()
{
    string cevap;
    char tekrar='y';
    while (tekrar!='n')
    {
      getline(cin,cevap);
      cout<<cevap<<endl;
      cout<<"Again? (y/n)";
      tekrar = cin.get();
      cin.ignore();
    }

    return 0;
}

This uses std::string and the non-member getline to 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). getline consumes and discards the delimiter, but get, used to read the continuation input, doesn't, so we discard it manually via ignore.

Upvotes: 5

Related Questions