2

I tried to input data with gets() function, but whenever program execution get to the the lien with the gets, it ignores it.

When I use gets() without previous data input, it runs properly. But when I use it after data input the problem happens.

Here's the code where it is used after previous data input (so in execution I can't input data to string):

int main() {
    char str[255];
    int a = 0;
    cin >> a;
    if(a == 1) {
        gets(str);
        cout << "\n" << str << endl;
    }
}

How could I fix this?

NB: the same happens with cin.getline

Hugo Dozois
  • 8,147
  • 12
  • 54
  • 58
  • 2
    You don't use gets(), ever! It's fundamentally unsafe and impossible to make safe. Also, don't mix C and C++ I/O. Now for cin.getline, it's a more interesting question which I just answered here: http://stackoverflow.com/questions/16405630/infile-open-refuses-to-read-the-variable-in-the-file – Sebastian Redl May 06 '13 at 20:04
  • 2
    Never, ever, ever use `gets`. You have no way to reliably avoid overrunning your buffer and causing all sorts of trouble. Use `fgets` instead, at the very least...but in C++, you'd almost always do better to use `std::getline(cin, a_std_string_variable)`. – cHao May 06 '13 at 20:04
  • Why does the title of this question say C, but the tags say C++? – Carl Norum May 06 '13 at 20:06
  • Because people confuse the two distressingly often. Since this is a C++ question, it may have been retagged by an editor. – This isn't my real name May 06 '13 at 20:12
  • 1
    As of the 2011 ISO C standard, `gets` has been removed from the language. – Keith Thompson May 06 '13 at 20:18
  • @SebastianRedl I'm not entirely sure, but `char buffer[10]; getchar(); ungetc('\n',stdin); gets(buffer);` might be a safe use of `gets()`. – Daniel Fischer May 06 '13 at 20:25
  • thanx for replying and being dynamic with me. Carl Norum: i mentioned c++ in title not c as u claim o.O –  May 06 '13 at 20:30
  • @DanielFischer Awesome! :D You have to add error handling for ungetc of course. (I thought unget/putback can only be used to return the actual characters read, but I was wrong.) – Sebastian Redl May 06 '13 at 20:31

1 Answers1

6

After

cin >>a

when you input a and enter, there is also a \n character left by cin, therefore, when you use cin.getline() or gets(str) it will read that newline character.

try the following:

cin >>a;
cin.ignore(); //^^this is necessary
if(a==1){
    gets(str);
}

You'd better use C++ way of reading input:

cin >> a;
cin.ignore();
string str;
if (a == 1)
{
   getline(cin, str);
}
taocp
  • 23,276
  • 10
  • 49
  • 62