This is a newbie program we had to write for our college test. The program asks for user to input a string, and then tells the user the number of characters in the string.
Here is the program
Code:
#include <iostream>
#include <string>
#include <conio.h>
#include <iomanip>
#include <stdio.h>
using namespace std;
struct text
{
string input_text;
int num_letters;
};
int main()
{
text count;
char responce = 0;
do
{
cout << "Please enter a string: ";
getline(cin, count.input_text);
count.num_letters = count.input_text.length();
cout << "The string " << count.input_text << " had "
<< count.num_letters << " characters." << endl << endl;
cout << "Would you like to enter another string (y or n) ?: ";
cin >> responce;
cout << endl << endl;
} while(tolower(responce) != 'n');
getch();
return 0;
}
The program works on the first run. But after the question "Do you want to enter another string ..." the program no longer works properly. The program does not give me a chance to enter another string if I answer 'y'. It's like the program automatically enters the string for me and gives me the answer. Here is what I am talking about
:
http://server4.uploadit.org/files/191103-error.png
I first thought that a newline character was stuck somewhere in the input buffer. I rewrote the program as follows:
Code:
#include <iostream>
#include <string>
#include <conio.h>
#include <iomanip>
#include <stdio.h>
using namespace std;
struct text
{
string input_text;
int num_letters;
};
int main()
{
text count;
char responce = 0;
do
{
cout << "Please enter a string: ";
getline(cin, count.input_text);
count.num_letters = count.input_text.length();
cout << "The string " << count.input_text << " had "
<< count.num_letters << " characters." << endl << endl;
cout << "Would you like to enter another string (y or n) ?: ";
scanf("%c", &responce);
fflush(stdin);
cout << endl << endl;
} while(tolower(responce) != 'n');
getch();
return 0;
}
================================================== =================
Works like a charm.
http://server4.uploadit.org/files/191103-no_error.png
'fflush(stdin);' did all the magic. Something did get stuck in the input buffer. My questions are: Can I replace fflush(stdin); or whatever else with something of C++ so that the program works? Why does this problem occur in the first place?
Thanks!