C++简单的计算器

Simple calculator in C++

本文关键字:计算器 简单 C++      更新时间:2023-10-16

我正在构建一个简单的计算器作为学习练习,但我磕磕绊绊 - 我得到了第一个数字的用户输入,但它无法存储第二个输入的 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;
}

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

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

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