I just started with C++ 11 Primer book, and currently on the section of if statements. I have previous experience with Java, but C++ input/output is really confusing me. I am putting multiple exercises in one file, just for convenience sake. However, it seems like since I called while (cin >> p)
it screws up my input for the question right below it.
I am using repel.it as my C++ code platform, and as such I am using a delimiter (!) to act as an end-of-file in my input for UNKOWN # OF INPUTS Section 1.4.3 question.
The problem occurs in Section 1.4.4, this line: if (std::cin >> currVal) {
. It does not wait for input, and instead just regards it as no input and skips over the if statement. I tried moving the std::cin >> currVal
out of the if statement to no avail (still does not read).
Here is an example input/output of my "program":
3825
10
9
8
7
6
5
4
3
2
1
Enter 2 Numbers:
6 9
6
7
8
9
0
3825
10
9
8
7
6
5
4
3
2
1
Enter as many numbers as you wish
5 4 3 2 1 5!
20
Here is my code:
#include <iostream>
int main() {
//WHILE LOOPS Section 1.4.1
//Exercise 1.9
int sum = 0, i = 50;
while (i <= 100) {
sum += i;
i++;
}
std::cout << sum << std::endl;
//Exercise 1.10
int j = 10;
while (j > 0) {
std::cout << j << std::endl;
j--;
}
//Exercise 1.11
int k, l;
std::cout << "Enter 2 Numbers: " << std::endl;
std::cin >> k >> l;
while (k <= l) {
std::cout << k << std::endl;
k++;
}
//FOR LOOPS Section 1.4.2
//Exercise 1.12
int sum1 = 0;
for (int m = -100; m <= 100; ++m) {
sum1 += m;
}
std::cout << sum1 << std::endl;
//Exercise 1.13
int sum2 = 0;
for (int n = 50; n <= 100; n++) {
sum2 += n;
}
std::cout << sum2 << std::endl;
for (int o = 10; o > 0; o--) {
std::cout << o << std::endl;
}
//UNKOWN # OF INPUTS Section 1.4.3
//Exercise 1.16
std::cout << "Enter as many numbers as you wish" << std::endl;
int sum3 = 0, p = 0;
while (std::cin >> p) {
sum3 += p;
}
std::cout << sum3;
//If Statement Section 1.4.4
int currVal = 0, val = 0;
if (std::cin >> currVal) {
int cnt = 1;
while (std::cin >> val) {
if (val == currVal) {
cnt++;
} else {
std::cout << currVal << " has occured " << cnt << " times." << std::endl;
cnt = 0;
}
}
std::cout << currVal << " has occured " << cnt << " times." << std::endl;
}
return 0;
}