是否可以使用scanf(“%d”和i)并使用仅输入的第一个数字,没有别的?

首先,我根本不熟悉c。 如果你把我当作一个初学者来对待我会很棒,我就是这样。

所以,我遇到的问题是我似乎无法做到这一点,以至于程序只获取一个数字的信息,使用它,然后忽略任何其他信息。

目前我有类似的东西:

#include  #include  int main(){ int i, ret; char c, type; do { printf("Convert ASCII # to character\n"); printf("q: Quit.\n"); scanf("%c", &type); /* I use the " if(type== 'n'); " a number of times. */ /* I left the others out to simplify what my problem is. */ if(type=='1'){ printf("ASCII NUMBER -> CHAR \n"); printf("\t Please input one ASCII code \n"); int ret = scanf("%d", &i); /* My aim here is to get the amount of integers the user inputs,*/ /* and use that to categorize, but I think I am failing to do so. */ if(ret==1){ printf("\t The character for ASCII code %d is -> '%c' \n\n", i, i); break; } else{ printf("Please input one number./n/n"); break; } } } while(type=='q'); return 0; /* A problem I face a lot is where the program would terminate*/ /* even when the while conditions weren't met. */ } 

我希望你能通过查看上面的代码来理解我想要做的事情。
任何帮助将不胜感激!

由于输入缓冲区中的字符[enter],程序结束。
然后为i输入类型的输入值,然后按[enter]。 这个[enter]是输入缓冲区中的一个字符,将被下一个读取

 scanf("%c",type); 

所以循环退出。 因此之后使用getchar()

 int ret = scanf("%d", &i); 

清除输入缓冲区。 并且循环不会意外结束。
进行这些更改,

  printf("\t Please input one ASCII code \n"); int ret = scanf("%d", &i); getchar(); //this will read the [enter] character in input buffer /* My aim here is to get the amount of integers the user inputs,*/ /* and use that to categorize, but I think I am failing to do so. */ if(ret==1){ 

一般来说,我发现使用fgets()更好(或者,如果你使用C99, gets_s() – 尽管我仍然喜欢fgets()以便为所有基于用户的输入提供最大的可移植性),那么如果必须使用sscanf()strtol()等将字符串转换为其他数据类型,因为这将以缓冲区安全的方式逐行读取数据,您不必担心剩下的内容。输入缓冲区。 对于基于用户的输入尤其如此,这种输入从来没有格式良好(由于拼写错误等)。 scanf()实际上只有在从格式良好的输入文件中读取时才能正常工作。

请参阅comp.lang.c FAQ,其中介绍了使用scanf()时经常出现的一些问题,包括您在上面看到的问题,其中输入似乎被跳过:

要了解有关任何C标准库函数的更多信息,请在linux命令提示符(或Google)中输入: man 3 fgets等。

  • fgets: http : //linux.die.net/man/3/fgets
  • sscanf: http : //linux.die.net/man/3/sscanf
  • strtol: http : //linux.die.net/man/3/strtol

例:

 char buffer[256], type; fgets( buffer, sizeof(buffer), stdin ); if( sscanf( buffer, "%c", &type ) == 1 ) { // Was able to read a char from the buffer, now you can use it. } else { // Wasn't able to read a char from the buffer. handle it if required. }