实例应用-scanf不接收空格和回车,gets()接收空格,不接收回车

半天不能通过,半天找不到错误,只改了一个地方立刻就ac了,欲知详情,请往下看:

K - The Marshtomp has seen it all before(然而沼泽鱼早就看穿了一切)

14184646038225.jpg

fjxmlhx不喜欢网上的 marshtomps 。所以他决定把所有的 “marshtomp”(名字不区分大小写) 改为 “fjxmlhx;

Input

输入包含多行,每行字符串不超过200的长度,一个单词不会一半出现在上一行,剩下的在下一行。直到文件结束(EOF)

Output

输出 替换之后的字符串。

Sample Input
The Marshtomp has seen it all before.
marshTomp is beaten by fjxmlhx!
AmarshtompB
Sample Output
The fjxmlhx has seen it all before.
fjxmlhx is beaten by fjxmlhx!
AfjxmlhxB


错误代码:

#include <stdio.h>
#include <string.h>
int main()
{
    int i;
    char a[10000];
    while(scanf("%s",a)!=EOF)
    {
        for(i=0;i<strlen(a);i++)
        {
            if((a[i]=='M'||a[i]=='m')&&(a[i+1]=='A'||a[i+1]=='a')&&(a[i+2]=='r'||a[i+2]=='R')&&(a[i+3]=='s'||a[i+3]=='S')&&(a[i+4]=='H'||a[i+4]=='h')&&(a[i+5]=='t'||a[i+5]=='T')&&(a[i+6]=='o'||a[i+6]=='O')&&(a[i+7]=='M'||a[i+7]=='m')&&(a[i+8]=='p'||a[i+8]=='P'))
        {
            a[i]='f';
            a[i+1]='j';
            a[i+2]='x';
            a[i+3]='m';
            a[i+4]='l';
            a[i+5]='h';
            a[i+6]='x';
            a[i+7]='0';
            a[i+8]='0';
        }
        }
        for(i=0;i<strlen(a);i++)
        {
            if(a[i]!='0')
                printf("%c",a[i]);
        }
        printf("\n");
    }
    return 0;
}

运行结果是:

The Marshtomp has seen it all before.
The
fjxmlhx
has
seen
it
all

before.

可以看到,它把每一个空格都当成了一个断句,也就是说scanf遇到空格或回车就认为这个句子已经输完了,空格后面的就是下一句话的内容。然而这并不是我们想要的,我们希望它它能完整地读完一句话,遇到回车表示结束。

所以,我们改一下代码,用gets()来接收句子。

改后正确代码:

#include <stdio.h>
#include <string.h>
int main()
{
    int i;
    char a[10000];
    while(gets(a))//从scanf改成了gets
    {
        for(i=0;i<strlen(a);i++)
        {
            if((a[i]=='M'||a[i]=='m')&&(a[i+1]=='A'||a[i+1]=='a')&&(a[i+2]=='r'||a[i+2]=='R')&&(a[i+3]=='s'||a[i+3]=='S')&&(a[i+4]=='H'||a[i+4]=='h')&&(a[i+5]=='t'||a[i+5]=='T')&&(a[i+6]=='o'||a[i+6]=='O')&&(a[i+7]=='M'||a[i+7]=='m')&&(a[i+8]=='p'||a[i+8]=='P'))
        {
            a[i]='f';
            a[i+1]='j';
            a[i+2]='x';
            a[i+3]='m';
            a[i+4]='l';
            a[i+5]='h';
            a[i+6]='x';
            a[i+7]='0';
            a[i+8]='0';
        }
        }
        for(i=0;i<strlen(a);i++)
        {
            if(a[i]!='0')
                printf("%c",a[i]);
        }
        printf("\n");
    }
    return 0;
}

运行结果:

The Marshtomp has seen it all before.
The fjxmlhx has seen it all before.

可以看到,只有一处改动

  while(gets(a))

被改动了。

半天不能通过,只改了这一个地方就ac了。。。已经不想说什么了微笑

猜你喜欢

转载自blog.csdn.net/nanfengzhiwoxin/article/details/80568748