c - 如何输入两个字符串?

标签 c

#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 后,我能够看到我的 gets 将换行符作为第一个字符串,然后正确地作为第二个字符串。 提前致谢

最佳答案

停止使用 stdinscanf() 读取输入。永远不要调用 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;
}

关于c - 如何输入两个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23135602/

相关文章:

汇编 (x86) 和进程切换的 C 回调函数

c - C语言中的限定符是什么?

c - 如何在 block 作用域中声明具有内部链接的标识符,而无需事先声明该标识符且某些链接可见?

c++ - 具有相邻位置 View 的 Win32 内存映射文件

c - 合并的链表

c - 在 C 中显示文件的所有者名称

java - 在 Java 和 C 上重现相同 HMAC MD5 的问题

c - scanf 函数无限接受值

c - 为什么 <linux/socket.h> 文件没有定义套接字类型?

c - 警告 : comparison between pointer and integer [enabled by default] in c