I am very much new into C++ and I ran into the following problem.
My goal:
I want to have a code which does the following:
- The user enters a line containing doubles separated somehow
- The doubles are being parsed into an array of doubles
- A computation(*) on the array takes place. For example its sum
- If the user doesn’t brake the loop, it reads a new line, and loop back to 1.
- Once the user broke the first loop (by entering empty line or something like that), a new one starts.
- The user enters a line containing doubles separated somehow
- The doubles are being parsed into an array of doubles
- A computation(**) on the array takes place. For example its average.
- User brakes the second loop.
- Program quits.
My code:
#include <iostream>
int main()
{
do {
double x1, x2, x3, y1, y2, y3;
std::cin >> x1 >> y1 >> x2 >> y2 >> x3 >> y3;
if (!std::cin){
break;
}
std::cout << "\n The sum is: " << (x1+y1+x2+y2+x3+y3) << "\n";
} while (1);
do {
double x1, x2, x3, y1, y2, y3;
std::cin >> x1 >> y1 >> x2 >> y2 >> x3 >> y3;
if (!std::cin){
break;
}
std::cout << "\n The average is: " << (x1+y1+x2+y2+x3+y3)/6 << "\n";
} while (1);
return 0;
}
The Problem:
When I try to stop the first loop, and move to the second by either hitting CTRL-D or giving a letter as input, then the program quits and skips the second loop. I realized that it relates to the cin mechanism, but I failed to cure it.
The question: How should I program this? What is the least painful manner to overcome the problem? Thanks in advance!
This is because when you try and read a letter or EOF (Ctrl-D) this sets the state of the stream into a bad state. Once this happens all operations on the stream fail (until you reset it). This can be done by calling clear()
I would not use this technique.
I would use something like an empty line as a separator between loop. Thus the code looks like this:
Try this:
Note: in C++ streams work best when numbers are space separated. So it is easy just use space or tab to separate the numbers.
// Or we could templatize the code slightly: