0

我需要编写一个程序,它要求您输入两个整数,然后输出相同的两个整数,但是如果您输入“|”,它将结束程序。

这就是我所拥有的,对我来说它应该工作,但不幸的是它没有。

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
#include <iomanip>
using namespace std;

int main()
{
    int var1 = 0;
    int var2 = 0;

    while(1)
    {
        cout << "Please enter two numbers.\n";
        cin >> var1;
        cin >> var2;

        if(var1 == '|')
            break;

        else
        {
            if(var2 == '|')
                break;

            else
            {
                cout << var1 << ' ' << var2 << '\n';
            }
        }       
    }
}

我确定这是我缺少的一些简单概念,但任何帮助显然将不胜感激。

4

4 回答 4

2

当您读取整数时,用户输入 like|只会导致(静默)错误,该错误会cin进入错误模式。

在错误模式被清除之前,进一步的输入操作将被忽略,因此您将获得无限循环。

std::getline而是使用来自标头的字符串将用户输入读取为字符串<string>。检查输入行是否以数字或“|”开头。如果是数字,则使用例如转换为整数std::stoi


该语言的无限循环内置语法是for(;;). 它的实际优势是 Visual C++ 不会发出关于常量条件表达式的愚蠢警告。

于 2014-09-24T04:41:48.767 回答
0

如果需要 int,请尝试将 var1 和 var2 声明为 char 类型,然后尝试

 if(var2 == 124)
于 2014-09-24T04:40:45.277 回答
0

如果您想接受数字以外的任何字符,则您的 var1 和 var2 不能是整数类型。所以你必须用 char 声明任何一个字符串。

我确定您将需要这两个数字来执行一些计算功能,因此将 var1 和 var2 从字符串类型转换为整数类型。

参考这个: http ://en.cppreference.com/w/cpp/string/basic_string/stol

这是对您关于“如何结束程序”的问题的回答

您可以使用

exit(1);

代码示例:

#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;

int main()
{
    string var1,var2;
    int num1,num2;

    cout << "Please enter two numbers.\n";
    cin>>var1;

    if(var1 != "|")
    {
        num1 = ::atoi(var1.c_str());
    }
    else
    {
        cout<<"Programs Terminated."<<endl;
        exit(1);
    }

    cin>>var2;

    if(var2 != "|")
    {
        num2 = ::atoi(var2.c_str());
    }
    else
    {
        cout<<"Programs Terminated."<<endl;
        exit(1);
    }

    cout<<"\nSum of 2 number: "<<num1+num2<<endl;
}
于 2014-09-24T04:49:16.137 回答
0

Instead of all the code starting from if(var1 == '|'), do this:

if ( !cin )
    break;

cout << var1 << ' ' << var2 << '\n';

When you use << to read into an int, and if the input does not actually contain an int, then it puts cin into a fail state . Testing !cin checks to see if cin is in the fail state.

To read more about this, read any C++ book or reference.

于 2014-09-24T04:50:08.893 回答