C ++中的简单计算器

时间:2012-09-21 09:39:00

标签: c++ windows

我正在构建一个简单的计算器作为学习练习而且我偶然发现 - 我获得了第一个数字的用户输入,但它无法存储第二个输入的int - 我是否需要创建对象?我认为这是一个明显的问题......

//Simple calculator to work out the sum of two numbers (using addition)

#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
    cout << "Enter the first int: \n";
    int input1 = std::cin.get();

    cout << "Enter the second int: \n";
    int input2 = std::cin.get();


    cout << "The sum of these numbers is: " << input1 + input2;
    cout << "\n";


    system("PAUSE");
    return EXIT_SUCCESS;
}

1 个答案:

答案 0 :(得分:9)

cin.get()只检索一个输入字符。为什么不使用

int input1, input2;
cout << "Enter the first int: \n";
cin >> input1;
cout << "Enter the second int: \n";
cin >> input2;

以这种方式使用std::cin(使用operator>>)也可以处理用户输入的任何剩余换行符或空格字符。