简体   繁体   English

在C中读取和打印字符串

[英]Reading and printing strings in C

I want to scan and print two strings one after another in a loop.But I cannot do it.Only one string gets scanned and printed if i use the loop.If i try to print without the loop then the two "gets()" work properly. 我想在一个循环中一个接一个地扫描并打印两个字符串。但是我做不到。如果使用循环,只有一个字符串被扫描并打印。如果我尝试不使用循环进行打印,则两个“ gets()”好好工作。

#include <stdio.h>

int main()
{
int T,i,j;
char name1[100];
char name2[100];
scanf("%d",&T);
for(i=0; i<T; i++)
{
    printf("Case %d: ",i+1);
    //scanf("%[^\n]s",name1);        
    gets(name1);
    /*for(j=0; j<strlen(name1); j++)
    {
        printf("%c",name1[j]);
    }*/
    puts(name1);
    //scanf("%[^\n]s",name2);
    gets(name2);
    /*for(j=0; j<strlen(name2); j++)
    {
        printf("%c",name2[j]);
    }*/
    puts(name2);
}
}

Here you go. 干得好。 Use fflush(stdin) . 使用fflush(stdin) It will take two inputs and print them one after the another. 这将需要两个输入,然后一个接一个地打印。

#include<stdio.h>

int main()
{
int T,i,j;
char name1[100];
char name2[100];
scanf("%d",&T);
for(i=0; i<T; i++)
{
    printf("Case %d: ",i+1);
    fflush(stdin);
    gets(name1);

    gets(name2);

    puts(name1);

    puts(name2);
}
return 0;
}

Edit: As suggested in the comment below, using gets() is not advisable if you do not know the number of characters you wish to read. 编辑:如下面的注释中所建议,如果您不知道要读取的字符数,则不建议使用gets()。

After taking testcase from the user, next line gets() function will take the '\\n' you have to ignore the scenario. 从用户获得测试用例后,下一行gets()函数将使用'\\n'您必须忽略该场景。

Here's a tricky solution of this problem. 这是此问题的棘手解决方案。 Just use '\\n' after %d in scanf function. 在scanf函数的%d之后仅使用'\\n' scanf("%d\\n",&T);

#include <stdio.h>

int main(void) {
    char s1[100],s2[100];
    int i,T;
    scanf("%d\n",&T);
    for(i = 0; i < T; i++){
        printf("Case %d: ",i+1);
        gets(s1);
        puts(s1);
        gets(s2);
        puts(s2);
    }
    return 0;
}

You do not terminate your prints. 您不终止打印。 stdout is buffered. stdout已缓冲。 Print is only performed after a "\\n" or explicit flush. 仅在“ \\ n”或显式刷新后才执行打印。 try something around the lines: 尝试一些方法:

#include <stdio.h>

int main()
{
    int T,i,j;
    char name1[100];
    char name2[100];
    scanf("%d",&T);
    for(i=0; i<T; i++)
    {
#ifdef BAD_CODE
        printf("Case %d: ",i+1);
        gets(name1);
        puts(name1);
        gets(name2);
        puts(name2);
        putchar("\n");
#else //better code
        fgets(name1, sizeof(name1)-1, stdin);
        fgets(name2, sizeof(name2)-1, stdin);
        printf("Case %d: '%s' '%s'\n",i+1, name1, name2);
#endif
    }
}

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

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