You didn't provide the part of the code which causes the problem. But I guess it looks a bit like this:
1 2 3
|
int numbers = 0;
cout << "Hello. How many numbers you wish to put in file: ";
cin >> numbers;
|
and how does it work? The message "How many numbers you wish to put in file:" is displayed. The user types "5" and then presses enter.
Now everything which the user types is held in the input buffer, including the enter key, which is stored as a newline character. The line
cin >> numbers;
will skip any leading whitespace, then read the numeric characters and put it into the variable
numbers
. As soon as some non-numeric character is encountered, the cin >> will stop reading, that means
the newline character is left in the buffer.
That has a knock-on effect for the following getline, which reads characters from the buffer until it reaches the newline, which is read and discarded. Thus
fileName
is read as an empty string, a line of length zero.
After that, the user is asked to enter the number,
cin>>floatNum
but instead the user types "average.txt" which of course is not a number. Hence the cin will fail and the loop will be executed repeatedly. The cin.ignore() will discard a single character of the text "average.txt" each time until eventually the buffer is emptied.
How to avoid this mess? After
cin >> numbers;
, clear the input buffer before the getline, by something like:
which will ignore up to 1000 characters, or until a newline is found, whichever comes first.
There are a few other issues with the code. The prompt message tells the user the program will read from the file, but the code
file<<floatNum<<endl;
is trying to write to the file, not read from it. I would change the text of the message to avoid the user accidentally overwriting some important file. The difference between read and write is not trivial.
Also the for loop at line 11 will output the same value to the file repeatedly which might not be what you actually want?