【问题标题】:String input in CC中的字符串输入
【发布时间】:2016-03-09 05:23:58
【问题描述】:

同时,每当我使用内置函数getsscanf 函数获取输入字符串和字符时,我都会遇到问题。

首先,每当我使用gets 获取输入字符串,然后在scanf 函数的帮助下输入一个字符时,编译器不会响应获取字符,尽管它从gets 函数获取输入并直接跳过scanf函数从用户那里获取一个字符。

查看下面的代码并将其运行到您的编译器以了解问题

   #include <stdio.h>
   #include <string.h>
   int main()
   {

  int i,l,T,exit;

  char str[1000];
  char ch;

  scanf("%d",&T);

  while( (T-- ) ){


       gets(str);

       scanf("%c",&ch);

       l = strlen(str);

       exit = 0;

       for( i = 0; i < l; i++ ){

            if( str[i] == ch )
                      exit++;
        }

       if(!(exit))
          printf("'\%c\' is not present\n",ch);

     else
         printf("Occurrence of '\%c\' in '\%s\' = %d\n",ch,exit);

    }

    return 0;

     }

【问题讨论】:

  • 你不应该使用gets(),它有不可避免的缓冲区溢出风险。
  • Couldn't reproducescanf() 似乎运行良好。
  • 它对我不起作用。如果我添加例如 printf("enter the char");或 fflush(NULL)。看起来 scanf 只是从流中获取第一个字符。正如你所指出的,应该使用gets。编译器也会发出同样的警告。我认为用 scanf 替换 OP 会更好。
  • 我建议扫描字符串并使用strchr() 函数检查字符串中是否存在字符。

标签: c string c-strings


【解决方案1】:

不要混用输入法。有关详细信息,请阅读此讨论。

http://c-faq.com/stdio/gets_flush2.html

我建议用scanf替换gets。

【讨论】:

    【解决方案2】:

    发现许多错误。试试这个,它应该可以正常工作

    #include<stdio.h> 
    #include<string.h>
    int main() 
    {
        int i, l, T, exit;
        char str[1000];
        char ch;
        scanf("%d", &T);
        while(T>0) {
            T--;
            scanf("%s", str);
            scanf(" %c", &ch);// Remember that there's a space next to %c
            l = strlen(str);
            exit = 0;
            for (i = 0; i < l; i++) {
                if (str[i] == ch)
                    exit=i+1;
            }
            if (!(exit))
                printf("'\%c\' is not present\n", ch);
            else
                printf("Occurrence of '\%c\' in '%s' = %d\n", ch, str, exit);
        }
        return 0;
    }
    

    请正确缩进你的代码

    【讨论】:

    • while (T--) 是所有必需的,但您应该检查scanf 的返回以确保您确实拥有T(T &gt; 0)
    • 改变了!谢谢@DavidC.Rankin
    • 它仍然无法使用 Sameera !并且使用您的代码,我仍然面临与以前相同的问题。
    • 你遇到了什么问题?
    猜你喜欢
    • 2021-08-25
    • 2020-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多