简体   繁体   English

为什么这个 c++ 程序不是 function 正确?

[英]Why does this c++ program not function correctly?

Right now, I'm learning C++.现在,我正在学习 C++。 I have made my first little program, an addition calculator.我制作了我的第一个小程序,一个加法计算器。 I write two numbers and it adds them.我写了两个数字,然后将它们相加。 Can you tell me why my output is 0?你能告诉我为什么我的 output 是 0 吗?

#include <iostream>
#include <string>
using namespace std;

int main () {
    int a;
    int b;
    string number1;
    string number2;
    number1 = a;
    number2 = b;
    int output;
    output = a + b;
    getline (cin, number1);
    getline (cin, number2);
    cout << output;
}

Output: Output:

1
1
0

Step through your code in order and you'll see the problem:按顺序单步执行您的代码,您将看到问题:

int main () {
    int a;
    int b;
    string number1;
    string number2;
    number1 = a;
    number2 = b;
    int output;
    output = a + b;
    getline (cin, number1);
    getline (cin, number2);
    cout << output;
}

You define four variables, fiddle with two of them in a weird way, and then calculate output as a+b.您定义了四个变量,以一种奇怪的方式摆弄其中两个,然后将 output 计算为 a+b。

By this point you haven't actually interacted with the user.到目前为止,您实际上还没有与用户进行交互。 You finish doing all that, and THEN you accept your two values (as strings) and output the previously-calculated value.你完成了所有这些,然后你接受你的两个值(作为字符串)和 output 之前计算的值。

You never use the values you pull in from input, as you do that after doing anything else.您永远不会使用从输入中提取的值,因为您在执行其他任何操作后都会这样做。

Maybe try this:也许试试这个:

#include <iostream>
#include <string>

int main () {
    std::string number1;
    std::string number2;
    std::getline (std::cin, number1);
    std::getline (std::cin, number2);

    int a = std::stol(number1);
    int b = std::stol(number2);
    int output = a + b;
    std::cout << output << std::endl;
}

That is, define your strings and then get them from the user.也就是说,定义您的字符串,然后从用户那里获取它们。

std::stol is "string to long". std::stol 是“字符串到长”。 It converts the strings to numbers.它将字符串转换为数字。

The rest should make sense. rest 应该有意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM