2

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.

Community
  • 1
  • 1
Vijay
  • 77
  • 1
  • 10

2 Answers2

3

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);
stardust
  • 5,918
  • 1
  • 18
  • 20
  • I think the second getline has to be removed from your code. With it, it doesn't ask for book_id after entering book_name – Vijay May 05 '13 at 11:12
  • @Vijay wouldn't there be a remaining `new line` character after the user enters the `book_name` and presses enter? – stardust May 05 '13 at 11:14
  • Right, I understand. Thanks for your reply. About your edit: "cin >> book_name;" accepts only 1 word of a multi word string. A book name can have multiple words. That's why I used gets – Vijay May 05 '13 at 11:20
1

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.

mtt
  • 106
  • 5