Reputation: 307
I'm just following a simple c++ tutorial on do/while loops and i seem to have copied exactly what was written in the tutorial but i'm not yielding the same results. This is my code:
int main()
{
int c=0;
int i=0;
int str;
do
{
cout << "Enter a num: \n";
cin >> i;
c = c + i;
cout << "Do you wan't to enter another num? y/n: \n";
cin >> str;
} while (c < 15);
cout << "The sum of the numbers are: " << c << endl;
system("pause");
return (0);
}
Right now, after 1 iteration, the loop just runs without asking for my inputs again and only calculating the sum with my first initial input for i. However if i remove the second pair of cout/cin statements, the program works fine..
can someone spot my error please? thank you!
Upvotes: 2
Views: 1761
Reputation: 26
I think you wanted this thing
In this case total sum c
will be less than 15 and continue to sum if user inputs y.
#include<iostream>
using namespace std;
int main()
{
int c=0;
int i=0;
char str;
do
{
cout << "Enter a num: \n";
cin >> i;
c = c + i;
cout << "Do you wan't to enter another num? y/n: \n";
cin >> str;
} while (c < 15 && str=='y');
cout << "The sum of the numbers are: " << c << endl;
return 0;
}
Upvotes: 0
Reputation: 28563
If you change
int str;
to
char str;
Your loop works as you seem to intend (tested in Visual Studio 2010).
Although, you should also probably check for str == 'n'
, since they told you that they were done.
Upvotes: 1
Reputation: 69958
...and only calculating the sum with my first initial input for i...
This is an expected behavior, because you are just reading the str
and not using it. If you enter i >= 15
then loop must break, otherwise continues.
Upvotes: 1
Reputation: 490038
After you read the string with your cin >> str;
, there's still a new-line sitting in the input buffer. When you execute cin >> i;
in the next iteration, it reads the newline as if you just pressed enter without entering a number, so it doesn't wait for you to enter anything.
The usual cure is to put something like cin.ignore(100, '\n');
after you read the string. The 100
is more or less arbitrary -- it just limits the number of characters it'll skip.
Upvotes: 4