【问题标题】:How to correctly handle scanf()如何正确处理scanf()
【发布时间】:2013-12-07 15:16:46
【问题描述】:

我必须接受以下格式的输入

S1 S2 S3

其中 S1 是字符,S2,S3 是整数 例如

 3
 A 123 452
 D 450 53
 B 330 672

(其中“3”代表查询次数) 现在我为它编写了以下代码:

 while(i<=Q){
          scanf("%c %d %d",&ch,&index,&num);
          printf("%c %d %d\n",ch,index,num);
          i++;
 }

但是,对于上面显示的三个值,我得到以下输出

 0 755130840
A 123 452

 123 452        

顶部有一条额外的线,并且那个大值(这里是 755130840)每次都在变化。

我哪里错了??我什至尝试单独扫描 3 个值并在每个扫描语句之前刷新输入流。但是,它也无济于事。

鉴于这两个空行,我相信换行符 ('\n') 被存储在某个变量中。我该如何处理它?

【问题讨论】:

  • 提示:使用返回值。 (是的:scanf() 有返回值!)
  • scanf%c前加一个空格
  • 这怎么行??是的,我的意思是它必须......但你能详细说明一下吗?(可能作为我可以投票的答案......:))
  • @alphacentauri 选择正确答案。

标签: c stdin scanf


【解决方案1】:

在 scanf 中的 %c 之前添加一个空格。这将允许 scanf 在读取 ch 之前跳过任意数量的空格。 scanf 带有空格会跳过空格(包括换行符)并读取下一个不是空格的字符。

这是一个代码,这会很好。

#include <stdio.h>

int main(void) {
    // your code goes here
    int i =0;
    int Q = 2;
    char ch;
    int index;
    int num;
    while(i<=Q){
          scanf(" %c %d %d",&ch,&index,&num);
          printf("%c %d %d\n",ch,index,num);
          i++;
 }

    return 0;
}

【讨论】:

  • -1,在这里发布代码。不要只用外部链接回答。
【解决方案2】:

你想要这样的东西吗?

#include <stdio.h>
#include <stdlib.h>

int main()
{

        int num, count, numone, numtwo;
        char charip;
        printf("Enter numbr of elem:\t");
        scanf("%d", &num);
        if (num < 0)
        {
                printf("Enter positive value!!!!!\n");
                exit (-1);
        }
        count = 0;
        while (count < num)
        {
                getchar();
                scanf ("%c %d %d", &charip, &numone, &numtwo)   ;
                printf("%c %d %d\n", charip, numone, numtwo);
                count++;
        }

        return 0;
}

【讨论】:

  • add count++ 否则会进入死循环
  • 你试过了吗...你怎么会忘记增加计数器?
  • 对不起..我的错。感谢 cmets。
猜你喜欢
  • 1970-01-01
  • 2016-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多