繁体   English   中英

以C中的空格取N个输入字符串

[英]Take N input strings with spaces in C

我试图将t(测试用例)字符串作为C中的输入。每个字符串都以#结尾,并且可以有空格。

我正在使用getchar和一些while循环,但无法实现我想要的功能。

int t;
scanf("%d",&t);

while(t>0){


        char expression[100];
        char c;

        int i=0;
        while(1){
            c = getchar();
            if(c == '#'){
                break;
            }
            else{
                expression[i]=c;
                i++;
            }

        }

        t--;


        printf("%d\n",i);
        for(int j=0;j<i;j++){
            printf("%c",expression[j]);
        }
      }

我要实现的目标是,如果遇到#,我想忽略它之后的所有内容。

我的输入:

1
test#wtf

输出:

5

test

因此,在1个测试用例的情况下,它工作正常。 但是当我尝试时。

2
test#wtf
test#

相应的输出是:

5

test

8
wtf
test

如您所见,第二个输出应为test ,长度应为5,但事实并非如此。

为了忽略#之后的文本,您必须使用getchar()使用这些字符,然后忽略它们,直到遇到换行符'\\n'为止。

因此,退出内部while循环后,您需要添加以下代码

while(1) {
    c = getchar();
    if(c == '\n'){
        break;
    }
}

您可以通过这种方式进行处理,处理所有字符,一旦获得“#”,便会继续读取字符而不将其添加到数组中,一旦获得新的行字符“ \\ n”,您便会退出外部循环。

while (--t > 0)
    {
        int i,s,c;
        char exp[100];

        s = 0;
        while (s < 100 && (c = getchar()) != '#')
            exp[s++] = c;
        while ((c = getchar()) != '\n')
            ;
        printf("%d\n", s);
        i = -1;
        while (++i < s)
            printf("%c", exp[i]);
        printf("\n");
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM