为什么它不从键盘输入字符串 [英] Why it don't take string input from keyboard

查看:76
本文介绍了为什么它不从键盘输入字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<stdio.h>
#include<string.h>

int main()
{
    int c,cas,i,j,sum=0;
    char a[100];
    scanf("%d", &cas);
    for(i=1;i<=cas;i++)
        {
            gets(a);
            c = strlen(a);
            for(j=1;j<=c;j++)
            {
               if(a[j]=='a' || a[j]=='d' || a[j]=='g' || a[j]=='j' || a[j]=='m' || a[j]=='p' || a[j]=='t' || a[j]=='w' || a[j]==' ')
                sum += 1;
               else if(a[j]=='b' || a[j]=='e' || a[j]=='h' || a[j]=='k' || a[j]=='n' || a[j]=='q' || a[j]=='u' || a[j]=='x')
                sum += 2;
               else if(a[j]=='c' || a[j]=='f' || a[j]=='i' || a[j]=='l' || a[j]=='o' || a[j]=='r' || a[j]=='v' || a[j]=='y')
                sum += 3;
               else if(a[j]=='s' || a[j]=='z' )
                sum += 4;
            }
            printf("Case #%d: %d\n",i,sum);
        }
return 0;
}

推荐答案

确实如此。

它只是没有做到 时,您希望。

使用调试器;在行上设置断点

It does.
It just doesn't do it when you expect.
Use the debugger; put a breakpoint on the line
for(j=1;j<=c;j++)

并运行您的代码。

输入您的整数并按ENTER键,它将点击断点。

c 将为零, a 将是一个空字符串 - 因为 scanf 调用将在满足ENTER时结束整数,但会将其保留在输入缓冲区中。所以当你尝试读取字符串时,有一个空行坐在那里等着你,然后它返回。

试试这个:

And run your code.
Enter your integer and press ENTER and it will hit the breakpoint.
c will be zero, a will be an empty string - because the scanf call will end the integer when it meets the ENTER, but will leave it on the input buffer. So when you try to read the string, there is a empty line "sitting there" waiting for you, and it returns that.
Try this:

int main()
{
    int c,cas,i,j,sum=0;
    char a[100];
    scanf("%d\n", &cas);
    for(i=1;i<=cas;i++)

它应该做你想象的。



我可以建议 if 代码会很多更可读的是你使用开关语句而不是如果

And it should do what you expected.

Can I suggest that the if code would be a lot more readable is you used a switch statement instead of if?


这篇关于为什么它不从键盘输入字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆