Strange behaviour with text input

I've got my code, here it is:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <fstream>
#include <iostream>
#include <conio2.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;

int main (int argc, char * argv [])
{
    unsigned int quan = 0;
    char txtinput[255] = "";
    unsigned int * pquan = &quan;
                 
    printf("Please, indicate the quantity of messages you want to display:");
    fscanf (stdin, "%u", &quan);
    while (quan != 0)
    {
         static int i = 1;
         cout << "Insert the " << i << "ยบ message:";
         /*->problem*/gets(txtinput);
         puts(txtinput);
         quan--;
         i++;
    }
    system ("pause");
    
}

The problem is that when the loop (while (quan != 0)) starts, the first input (puts(txtinput)) doesn't work. I mean, the program doesn't give me the possibility to write anything, but in the second part of the loop it does. What's the problem there?
try getline() instead of gets()

Edit: don't use scanf, it's C not C++.
Last edited on
You should review the <<C++ Primer 4th>>
That doesn't answer the question though, and the very same caveat will hit you with the standard C++ streams as in C.

The scanf() functions and the C++ stream extraction operators all halt on whitespace. So on line 15 you get an unsigned int, but leave the '\n' in the input.

So the first time you hit line 20 it reads that '\n' and returns an empty string. To fix that, you need to first rid the input of that extraneous newline. In C, you can change line 15 to

fscanf( stdin, "%u\n", &quan );

In C++ it would be:
1
2
cin >> quan;
cin.ignore( numeric_limits <streamsize> ::max(), '\n' );


Hope this helps.
OK, let me try this in your way itself.

Just add the following line:
 
fflush(stdin);


immediately after your
fscanf (stdin, "%u", &quan);


This will flush out any input/output buffer of stream. In this case, it is stdin; the buffer is still in there waiting to be used and you are attempting to input some more immediately, then it would skip the next immediate input attempt.

Hope this helps.

Good luck :)
Last edited on
Except that fflush() is not defined on input streams.
Syntactically it is for an output stream. In this case, stdin (input stream) is flushed out before another input.

Try it out. Good luck :)
Topic archived. No new replies allowed.