سؤال

I am learning about classes in C++. I made a simple program using the concept of classes. In the program I need the person to enter the details of the book. Here is that function:

void Book::add(){
cout << "Enter name of Book: ";
gets(book_name);gets(book_name);
cout << "\n\nPlease enter the book id: ";
cin >> book_id;
cout << "\n\nThank you the book has been added.";
total++;
input = getchar();
getchar();
}

Notice in the third line I have to use two gets to get the user input. If I use one gets this is the output. It just skips the gets statement. Similarly at other places also I have to use two getchar statements. I was able to find the answer for that on SO itself. Ex Why my prof. is using two getchar. I couldn't find the answer for two gets statements, though. Here is the complete code in case it is required.

هل كانت مفيدة؟

المحلول

That is because you have a trailing new line (from Enter) character remaining on the stream that is not read by the first read operation. So the first gets(book_name) will read that and continue to the next request for input.

use getline to remove any remaining offending input from the stream.

void Book::add(){
    string garbage;
    getline(cin,garbage);  // this will read any remaining input in stream. That is from when you entered 'a' and pressed enter.
    cout << "Enter name of Book: ";
    gets(book_name);
    getline(cin,garbage);  // this will read any remaining input in stream.
    cout << "\n\nPlease enter the book id: ";
    cin >> book_id;

Anyways just use the safer way of reading input from streams

cin >> book_name;

instead of gets. Then you will not have such problems.


if you want to read space separated inputs in to one string the use std::getline (like I did for garbage above)

std::getline(cin,book_name);

نصائح أخرى

cin and cout are from <iostream> and gets comes from <cstdio>. It's not good idea to mix those two if you don't exactly know how those two work and what is the difference.

Better idea is to use cin.getline()

cin.getline(char* s, streamsize n );

The second parameter is the maximum length of the input.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top