Reputation: 37
I have used a loop for that:
int number1;
int sum = 0;
for(int i=1; i<6; i++) {
cout << "Enter number:\n";
cin >> number1;
sum += number1;
}
cout << sum;
cout << "Total Sum is = " << sum << "\n";
return 0;
}
How I can print the first statement like the following?
"Enter first number"
Enter Second number" and so on
Upvotes: 0
Views: 2868
Reputation: 84551
Whenever you are reading numbers (or any value for that matter), you must check the stream-state (see: std::basic_istream State Functions). You have four stream states you must test following every input:
.bad()
or .eof()
. If badbit
is set, an unrecoverable error occurred, and if eofbit
is set, there is nothing more to read (you can combine both into a single test that exits if either are set)
.fail()
is set when a read error occurs, such as the user entering "FIVE"
instead of 5
where integer input is expected. You handle failbit
being set by calling .clear()
to clear failbit
and then call ignore()
to empty the characters causing the failure before your next read attempt, and finally
.good()
- valid input was received from the user, you can proceed to the next input.
By validating your input here, you can Require the user provide five valid integer values for you to sum. Do not use a for
loop, instead use a while
(or do .. while();
) and only increment your counter when good input is received.
Putting that altogether, you can do:
#include <iostream>
#include <limits>
int main (void) {
int number = 0,
sum = 0;
const char *label[] = { "first", "second", "third", "fourth", "fifth" };
while (number < 5) /* Loop continually until 5 int entered */
{
int tmp; /* Temporary int to fill with user-input */
std::cout << "\nenter " << label[number] << " number: ";
if (! (std::cin >> tmp)) { /* Check stream state */
/* If eof() or bad() exit */
if (std::cin.eof() || std::cin.bad()) {
std::cerr << " (User canceled or unrecoverable error)\n";
return 1;
}
else if (std::cin.fail()) { /* If failbit */
std::cerr << " error: invalid input.\n";
std::cin.clear(); /* Clear failbit */
/* Extract any characters that remain unread */
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
}
else { /* On successful read of int, add to sum, increment number */
sum += tmp;
number++;
}
}
std::cout << "\nsum: " << sum << '\n';
}
Now your code will gracefully handle an invalid input without exiting just because a stray character was entered.
Example Use/Output
When you write an input routine, go try and break it. Enter invalid data and make sure you handle all error cases correctly. If something doesn't work right, go fix it. Repeat until you input routine can handle all corner cases as well as the cat stepping on the keyboard:
./bin/sumintlabel
Session transcript:
enter first number: 3
enter second number: four five six seven!!
error: invalid input.
enter second number: 4
enter third number: 5
enter fourth number: 6
enter fifth number: 7
sum: 25
Form good habits now regarding handling input; it will pay dividends for the rest of your programming career. Let me know if you have questions.
Upvotes: 3
Reputation: 128
If you need to print the words "first"... until "fifth", then I'd do it like this:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
int number1;
int sum = 0;
string positions[5] = {"first", "second", "third", "fourth", "fifth"};
for(int i = 0; i<5; i++) {
cout << "Enter the " << positions[i] << " number:" << endl;
cin >> number1;
sum += number1;
}
cout << "Total Sum is = " << sum << "\n";
return 0;
}
I used an array of strings to display the words and changed the for loop to start at 0m, so that we can go through the array positions and add the five numbers as well. If you just want to use: 1st, 2nd, 3rd... then you could change the for loop to what it was and do:
cout << "Enter the " << i << "st" << " number:" << endl;
But for this, you would have to use the if statement to print the right endings ("st", "rd", and "nd"). I think it would take longer for it to run, but it’s milliseconds, so we wouldn't even notice, hahaha.
Upvotes: 0
Reputation: 880
You can use switch()
:
#include <iostream>
using std::cin;
using std::cout;
using std::string;
int main() {
int number1;
int sum = 0;
for(int i = 1; i < 6; i++) {
string num;
switch(i) {
case 1:
num = "first";
break;
case 2:
num = "second";
break;
//and 3 4 5 like this
}
cout << "Enter " << num << " number:\n";
cin >> number1;
sum += number1;
}
cout << "Total Sum is = " << sum << "\n";
return 0;
}
or you can use struct or containers like vector (in fact you have to use containers if you want to get a huge number of data.)
Upvotes: 0