循环时不能退出,(C ++)?

时间:2013-11-13 22:08:27

标签: c++ while-loop

这里我尝试了一个“C ++入门”的例子,然而,它停留在while循环中。 这是我的代码:

#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;
}

请告诉我这是怎么回事,我真的很感激 干杯 Eason.li

4 个答案:

答案 0 :(得分:9)

输入下一个值并按Enter键后,您应该按Ctrl + z组合键(在Windows中)或Ctrl + d键(在Unix中)

答案 1 :(得分:1)

只是在你的while子句中输入一个条件

std::cin >> value;
while (value != 0)
{
    sum += value;
    std::cin >> value;
}

或者

do
{
    sum += value;
    std::cin >> value;
}while(value != 0);

答案 2 :(得分:1)

你需要在while循环中有一个条件

while (value !=0)

答案 3 :(得分:0)

#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;
}