【问题标题】:Using scanf to read a string then a integer, reads string only使用 scanf 读取字符串然后读取整数,仅读取字符串
【发布时间】:2014-04-27 15:43:56
【问题描述】:

我正在尝试使用两个 scanf 读取一个字符串,然后读取一个整数。程序等待我输入字符串,我按回车键,然后不等我插入整数。我正在使用的代码:

printf("Insert the name of the author to search: ");
scanf("%300s", author);

printf("Insert the year: ");
scanf("%d", &year);

有什么建议吗?

【问题讨论】:

  • 您为第一个scanf() 输入的输入是什么?
  • 注意:如果代码有char author[301],则使用"300" 是有意义的。但如果代码有char author[300],格式中使用"299"。

标签: c string int scanf


【解决方案1】:

转换说明符 "%s" 在空格处中断。

例如,如果您输入“John Smith”,则变量author 将具有"John",其余输入将用于year。

始终验证(大多数)库函数的返回值。

printf("Insert the name of the author to search: ");
if (scanf("%300s", author) != 1) /* error */;

printf("Insert the year: ");
if (scanf("%d", &year) != 1) /* error */;

获取用户输入的最佳方式是使用fgets(),然后,如果需要,解析输入并分配给变量。

char tmp[1000];

printf("Insert the name of the author to search: ");
if (!fgets(tmp, sizeof tmp, stdin)) /* error */;
strcpy(author, tmp);

printf("Insert the year: ");
if (!fgets(tmp, sizeof tmp, stdin)) /* error */;
if (sscanf(tmp, "%d", &year) != 1) /* error */;

【讨论】:

  • "%300s" 说明符似乎解决了中断 withespace 的问题。由于需要进行所有额外的解析,我试图避免 fgets,这难道不能只用 scanf 来解决吗?
  • @pmg 后面的换行符怎么办?
  • scanf() 有一个 scanset 说明符。您可能想尝试一下:if (scanf("%300[a-z A-Z0-9,.]", author) != 1) /* error */;
  • 换行符是空格,scanf() 说明符 "%s" 忽略换行符。
  • if (scanf(" %300[a-z A-Z0-9,.]" 将有助于消耗领先的空白。
【解决方案2】:

您正在尝试将输入读入author 数组,其中输入长度最多可以为 300 个字符,所以我希望您已将数组大小声明为char author[301],300+1(额外的一个用于容纳 '\0' )。

你可以使用scanf(" %300[^\n],author")这样的函数,这意味着继续从键盘(或者你可以说键盘缓冲区)读取字符,直到找到'\n',并且当你按下Enter键时生成'\n',因此我们强制scanf() 读取字符,直到我们按下回车键。

我们可以使用fgets(),但问题之一是它甚至会将'\n' 读入数组,这总是会在一个额外的新行上打印下一个printf() operation 的输出。这可能会导致问题你希望你的输出是表格形式。

int main()
{
   char author[301]="\0";//initialize char array to '\0' NULL's
   int year;
   printf("Insert the name of the author to search: ");

   if( scanf(" %300[^\n]", author)!=1 )
   {
       printf("End of Input or Error Occurred reading Name.\n");
       return 1;// return (NON-ZERO) means unsuccessful termination
   }

   printf("Insert the year: ");
   if( scanf("%d", &year)!=1 )
   {
       printf("End of Input or Error Occurred reading Year.\n");
       return 1;// return (NON-ZERO) means unsuccessful termination
   }    
return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-03
    • 1970-01-01
    • 2013-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多