gpt4 book ai didi

c - 将三个单词准确读入一个字符数组

转载 作者:太空宇宙 更新时间:2023-11-04 00:38:44 24 4
gpt4 key购买 nike

我要使用的变量数量有限,所以我想只使用一个变量来解决以下问题。可能吗?

  char str[100];
// Type three words:
printf("Type three words: ");
scanf("%s %s %s",str,str,str);
printf("You typed in the following words: \"%s\", \"%s\" and \"%s\"\n",str,str,str);

以下输入给出以下输出:

Type three words: car cat cycle
You typed in the following words: "cycle", "cycle" and "cycle"

这并不奇怪,因为最后读取的单词存储在同一 char 数组的开头。有什么简单的解决方案吗?

最佳答案

使用循环?

char buf[0x100];

for (int i = 0; i < 3; i++) {
scanf("%s", buf);
printf("%s ", buf);
}

旁注:但为什么不一次读取整行,然后使用 e 解析它呢? G。 strtok_r()?

fgets(buf, sizeof buf, stdin);

是要走的路...

关于c - 将三个单词准确读入一个字符数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18031483/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com