繁体   English   中英

如何取两个字符串的输入?

[英]how to take input of two string?

#include <stdio.h>
#include<stdlib.h>
#include <string.h>
int main(void) {
    char a[1001];
    int t,i;
    scanf("%d",&t);

    while(t--)
    {
        fflush(stdin);
        gets(a);
        printf("%d\t",t);
        puts(a);

    }
    return 0;
}

输入:

2 
die another day.
i'm batman.

输出:

1   
0   die another day.

预期产量:

1    die another day.
0    i'm batman.

任何人都请帮助如何接受多个字符串而没有任何错误。 输入2后,我可以看到我的获取正确地将换行符用作第一个字符串,然后将第二个字符串正确地用作。 提前致谢

停止使用stdin输入的scanf()读取输入。 不要调用fflush(stdin); 要么,但是如果您停止使用scanf()您将不再想要。

使用fgets()将整行读取到适当大小的字符串缓冲区中,然后解析得到的内容。 sscanf()是解析字符串的一个很好的功能,它与scanf()只不过它从字符串中读取。

这将更容易,不那么烦人,并且通常会更好。 哦,当然不要使用gets()

像这样(未经测试):

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
  char line[256];

  if(fgets(line, sizeof line, stdin))
  {
    int count;
    if(sscanf(line, "%d", &count) == 1)
    {
      while(count > 0)
      {
        if(fgets(line, sizeof line, stdin))
        {
          printf("%s", line);
          --count;
        }
        else
          break;
      }
    }
  }
  return EXIT_SUCCESS;
}

不要使用fflush(stdin)。 使用getchar()清除scanf()之后的[enter]字符,

#include <stdio.h>
#include<stdlib.h>
#include <string.h>
int main(void) {
    char a[1001];
    int t,i;
    scanf("%d",&t);
     getchar();
    while(t--)
    {

        gets(a);
        printf("%d\t",t);
        puts(a);

    }
    return 0;
}

有用。

暂无
暂无

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

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