Reputation: 1
I want to show the output like below:
Count Input Total
----- ------ -----
1 2 2
2 4 6
3 6 12
4 8 20
Average : 5
Here is my try:
int count=1,num,total=0;
cout<<"Count Input Total"<<endl;
cout<<"----- ----- -----"<<"\n";
while(count<=4)
{
cout<<count<<"\t";
cin>>num;
total=total+num;
cout<<"\t\t"
<<total<<endl;
count++;
}
cout<<"Average : "
<<total/4;
return 0;
}
but it comes out like this:
Count Input Total
----- ----- -----
1 2
2
2 4
6
3 6
12
4 8
20
Average : 5
--------------------------------
Process exited after 5.785 seconds with return value 0
Press any key to continue . . .
Upvotes: 0
Views: 4940
Reputation: 4615
You are mixing the output from your program with the input from the keyboard, both of which are being displayed on the same console.
The input from the console taken by cin>>num will only be received after you have pressed "enter" on the keyboard, and that in turn will also cause the output on the screen to go to the next line.
If you want to suppress the "enter" from moving the cursor the next line on the screen, this cannot be done easily from c++, typically there are ways in Linux or Windows or other operating systems from doing so (stty -echo, echo off, and so on). But then that will also suppress the typed integers from appearing, so in your code you would need to print them out as they come in.
However, people usually do not attempt to mix output from the keyboard with output from a program into coherent things like tables. You program could simply ask for keyboard input first, store that input into an array or vector, and then using that input write your table afterwards. Most likely that is what the question has asked you to do.
#include <iostream>
#include <vector>
using namespace std;
void output(vector<int> &vals) {
unsigned int count = 1;
int total = 0;
cout << "Count\tInput\tTotal" << endl;
cout << "-----\t-----\t-----" << endl;
while (count <= vals.size()) {
int num = vals[count - 1];
total += num;
cout << count << "\t" << num << "\t" << total << endl;
count++;
}
cout << "Average : " << total / (count - 1) << endl;
}
vector<int> input() {
vector<int> vals;
for (int i = 0; i < 4; i++) {
int num;
cin >> num;
vals.push_back(num);
}
return vals;
}
int main() {
output(input());
}
5
7
2
11
Count Input Total
----- ----- -----
1 5 5
2 7 12
3 2 14
4 11 25
Average : 6
Upvotes: 1