【发布时间】:2019-05-04 01:11:54
【问题描述】:
这里是编程菜鸟。我有一个作业,我必须使用getchar() 读取一个数字并对其执行一些操作。该数字可以是正数或负数。这是我的代码中接受输入的部分。我找不到问题,但它返回了其他内容。
我正在使用将字符转换为整数的一般方法,首先将累加器乘以10,然后使用(ch -'0') 将字符转换为其等效数字并将其添加到累加器中,
我已尝试删除对负数的验证,但仍然没有任何区别。
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <math.h>
int main() {
int accumulator = 0;
char ch;
int negative = 0;
ch = getchar();
if (ch == '-') {
negative = -1;
ch = getchar();
}
if (isdigit(ch) == 0) {
puts("\nError: Not valid number.\nPlease try again");
EXIT_FAILURE;
}
while ((ch = getchar()) != '\n') {
ch = getchar();
if ((ch = getchar()) == EOF) {
break;
}
if (!isdigit(ch)) {
puts("\nError: Not valid number.\nPlease try again");
break;
EXIT_FAILURE;
}
accumulator = accumulator * 10;
accumulator = (ch = '0') + accumulator;
}
if (negative == -1)
accumulator = accumulator * negative;
printf("%d", accumulator);
}
例子
输入:2351
输出:2351(使用getchar)
输入:-5689
输出:-5689(使用getchar)
【问题讨论】:
-
您的代码在您的两个示例中似乎都成功了。你能举个失败的例子吗?
-
while循环多次调用getchar()。它在while()条件中调用它一次,然后在第一行再次调用它。所以它在while()中测试的字符被忽略了。然后它在if ((ch == getchar()) == EOF)中再次调用它,因此它在上一行读取的字符被忽略。 -
@Beta 我认为底部的示例是它应该返回的,而不是它实际返回的。
-
@AlistairAlva:您可以通过单击其分数下方的灰色复选标记来接受其中一个答案