Unable to recive string

Hey everybody,

I have a problem with the line "gets_s(temp, 80);".
the progrem do not able me to enter a string.
the problem exist only when I put the line above at the "loop" ("case 0")

somebody can help me?




using namespace std;

int main()
char temp[80];
char** lexicon;
int size = 0; // "size" is the amount of words at the lexicon.
lexicon = new char*[size];
int choice;
do {
cout << "enter 0-5" << endl;
cin >> choice;
switch (choice) {
case 0: // adding a new word
cout << "enter the word: " << endl;
gets_s(temp, 80);
//newStr(lexicon, size, temp);
//printAll(lexicon, size);
case 1:
case 2:
case 3:
case 4:
case 5: break;
default: cout << "ERROR" << endl;
} while (choice != 5);

/*for (int i = 0; i < size; i++)
delete[] lexicon[i];
if (size > 0)
delete[] lexicon;*/
Last edited on
The immediate problem is that the cin input stream is buffered. After entering a value for choice, the enter key is pressed. That is stored in the input buffer as a newline character '\n'.

When the gets_s() is executed, it reads up to the next newline character, meaning it reads an empty string and doesn't give the user a chance to type anything.

Solution, after the cin >> use ignore() to remove the unwanted newline from the buffer. Possibly like this:

    cin  >> choice;
    cin.ignore(1000, '\n'); 
Thank you Chervil!

You helped me to contine at my progrem.
why you inserted the number "1000" at the function "cin.ignore"?
why you inserted the number "1000" at the function "cin.ignore"?
I did that partly out of habit, I use it a lot.

But the meaning is this. Suppose the user when typing the value for choice types something like this:
"3 " or "3 fgdyui ".

Any of those would be acceptable, the variable choice receives the value '3' and the remainder of anything the user may have typed (whether deliberately or accidentally) will remain in the input buffer.

    cin.ignore(1000, '\n');

tells the program to read and discard up to 1000 characters from the buffer. Or until a newline character is reached, whichever comes first. It is a precaution to guard against unpredictable input.

There is a longer form which will ignore any number of characters, or until the delimiter is found. It looks like this:
    std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );

That would be better. If you were writing a serious program than you would use that. (requires the header #include <limits> ).
Topic archived. No new replies allowed.