Reputation: 683
here im trying a example from "C++ primer", however, it stuck at while loop. Here is my codes:
#include<iostream>
int main()
{
int sum =0 , value =0 ;
while (std::cin >> value)
{
sum += value;
}
std::cout << "sum is: " << sum << std::endl;
//system("pause");
return 0;
}
Please tell me how is it wrong, i will really appreciate that Cheers Eason.li
Upvotes: 2
Views: 1095
Reputation: 77
#include <iostream>
#include <string>
using namespace std;
int main()
{
bool input=true;
int sum =0 , value =0 ;
while (input)
{
string choice;
std::cout << "Enter Value to be added to sum"<<std::endl;
std::cin>>value;
sum += value;
std::cout<<"add another value?"<<std::endl;
std::cout<<"Enter yes or no"<<std::endl;
std::cin>>choice;
if(choice=="yes")
input=true;
if(choice=="no")
break;
}
std::cout << "sum is: " << sum << std::endl;
system("pause");
return 0;
}
Upvotes: 0
Reputation: 31204
just put a condition to exit in your while clause
std::cin >> value;
while (value != 0)
{
sum += value;
std::cin >> value;
}
or, alternatively
do
{
sum += value;
std::cin >> value;
}while(value != 0);
Upvotes: 1
Reputation: 311058
After entering a next value and pressing the Enter key you should press combination Ctrl+z (in Windows ) or Ctrl + d ( in Unix)
Upvotes: 9