【问题标题】:Storing a string of words in a data structure在数据结构中存储一串单词
【发布时间】:2018-08-25 04:54:00
【问题描述】:

我想创建一个程序,它接收来自用户的一些输入词,将输入存储在数据结构中,然后将数据结构打印到 txt 文件中。

现在我只构建了它接收一些输入并将它们存储在数据结构中的部分,然后我添加了一个 printf 来打印数据结构,只是为了测试。

问题是,如果我在字符“one”上输入“test_one”,它将打印“test_one”,但如果我输入“test one”,它只会打印“test”。 我如何编辑它以便它存储整个单词而不是只存储一个单词?我可以用指针来做吗?

#include <stdio.h>

struct inputs {
   char one[30];
   char two[30];
   char three[30];     
};

int main(void)
{  

   struct inputs inputs = {"", "", ""};
   scanf("%s%s%s", inputs.one, inputs.two, inputs.three);

   printf("\n%s;%s;%s\n", inputs.one, inputs.two, inputs.three);


   } 
} 

【问题讨论】:

  • 谢谢!我只知道gets,不知道fgets

标签: c data-structures


【解决方案1】:

带有标准“%s”的scanf 只会读取输入,直到它到达一个空格。尝试阅读直到换行:

scanf("%[^\n]s", inputs.one);
scanf("%[^\n]s", inputs.two);
scanf("%[^\n]s", inputs.three);

【讨论】:

  • 一个问题:为什么只需要一个输入?它只运行第一个 scanf 而忽略其他两个
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多