14

我想将用户输入作为整数处理,但似乎 C 无法从标准输入获取 int。有这样做的功能吗?我将如何从用户那里获得一个 int ?

4

5 回答 5

23
#include <stdio.h>

int n;
scanf ("%d",&n);

http://www.cplusplus.com/reference/clibrary/cstdio/scanf/

于 2009-05-14T19:44:32.500 回答
6

scanf()是答案,但你当然应该检查返回值,因为从外部输入解析数字时很多很多事情都会出错......

int num, nitems;

nitems = scanf("%d", &num);
if (nitems == EOF) {
    /* Handle EOF/Failure */
} else if (nitems == 0) {
    /* Handle no match */
} else {
    printf("Got %d\n", num);
}
于 2009-05-14T20:01:59.400 回答
2

除了(f)scanf已在其他答案中充分讨论的 之外,还有atoiand strtol,用于您已经将输入读入字符串但想要将其转换为intor的情况long

char *line;
scanf("%s", line);

int i = atoi(line);  /* Array of chars TO Integer */

long l = strtol(line, NULL, 10);  /* STRing (base 10) TO Long */
                                  /* base can be between 2 and 36 inclusive */

strtol推荐使用它,因为它允许您确定一个数字是否被成功读取(与 相反atoi,它无法报告任何错误,并且如果它给出垃圾则只会返回 0)。

char *strs[] = {"not a number", "10 and stuff", "42"};
int i;
for (i = 0; i < sizeof(strs) / sizeof(*strs); i++) {
    char *end;
    long l = strtol(strs[i], &end, 10);
    if (end == line)
        printf("wasn't a number\n");
    else if (end[0] != '\0')
        printf("trailing characters after number %l: %s\n", l, end);
    else
        printf("happy, exact parse of %l\n", l);
}
于 2009-05-14T20:57:46.943 回答
1

标准库函数scanf用于格式化输入:%d int(d 是十进制的缩写)

#include <stdio.h>
int main(void)
{
  int number;
  printf("Enter a number from 1 to 1000: ");

  scanf("%d",&number); 
  printf("Your number is %d\n",number);
  return 0;
} 
于 2009-05-14T19:48:04.487 回答
-1
#include <stdio.h>

main() {

    int i = 0;
    int k,j=10;

    i=scanf("%d%d%d",&j,&k,&i);
    printf("total values inputted %d\n",i);
    printf("The input values %d %d\n",j,k);

}

这里

于 2009-05-14T19:45:16.243 回答