【发布时间】:2021-10-22 13:27:59
【问题描述】:
#include <iostream>
using namespace std;
int Variable() {
char Letter= ' ';
cout << "Your Name: ";
cin >> Letter;
cout << "Your first Letter is : " << Letter;
return 0;
}
int userInput(int number)
{
int input = 0;
cout << "Give me your " << number << ". number: ";
cin >> input;
cout << "\n";
return input;
}
int main() {
Variable();
int input1 = 0;
int input2 = 0;
input1 = userInput(1);
input2 = userInput(2);
cout << "Result: " << (input1 * input2) << "\n\n";
return 0;
}
输出:
Your Name: Kevin
Your first Letter is : K
Give me your 1:
Give me your 2:
Result: 0
我在控制台中写了一个名字,然后我得到了第一个字母,但是之后我不能输入这两个数字,因为程序结束了。我不明白为什么程序会跳过 userInput 函数。
【问题讨论】:
-
使用调试器单步调试代码。请注意,
cin >> input失败。因为evin不是有效整数。 -
“我不明白为什么程序会跳过 userInput 函数。” -- 你的输出表明该函数没有 被跳过,因为那是
Give me your 1:和Give me your 2:行的来源。更准确地说,您的困惑在于该函数中的一行。 (调试时精度很重要。) -
也许您希望对方输入他们的名字而不是单个字符。如果是这样
char Letter= ' ';应该是std::string firstName;并更新代码以使用新变量。这样说的名字有点困难,因为如果这个人进入一个空间,那么空间之后的所有东西都将留在缓冲区中以供下一个输入,从而导致与当前代码相同的问题。我提到这一点是因为有些人的名字像Mary Jo -
请尝试以更好的方式提问:问题标题是通用的,对将来可能搜索相同内容的人没有用,并且您没有描述您为解决问题所做的任何努力问题。
-
如果您想回答自己的问题,可以这样做。但是,您不应该通过编辑您的问题来回答。通过发布答案来回答。