我是C的新手,所以一些澄清会非常有帮助!我正在尝试使用扫描仪向我的程序询问一系列我将要存储的单词。到目前为止,我的目标是什么,
char[]listOfWords[9999]; //creates a large array of characters
scanf("%s", listOfWords); //stores inputs into listOfWords
有了这个,我可以很容易地访问第一个单词,但它涉及访问第二个,第三个单词的问题......有什么建议吗?例如,我的输入是
Hello how are you guys
我可以访问“Hello”没问题,但我怎么称呼“how”和“are”
答案 0 :(得分:1)
这个 - char[]listOfWords[9999];
不是声明数组的有效语法。
您只需要声明一个数组 -
char s[100];
fgets(s,100,stdin); // take input and store it in s
使用strtok
或sscanf
,您可以在不同的数组中提取单独的单词。
或者您可以使用二维数组 -
char s[100][100];
因此,如果存储在其中的字符串是 - Hello how are you guys
然后按s[0]
,您将获得Hello
,s[1]
将获得how
,同样地,其他字词也会显示在字符串中。
答案 1 :(得分:1)
Scanf()只接受单个单词的输入。(不在空格之后。)
要输入多个字词,您可以使用获取(字符串)或 scanf(“%[^ \ n]”,字符串)。
答案 2 :(得分:0)
你的问题是读多个单词吗?或者只是读一整行?声明char[]listOfWords[9999]
也是错误的。如果你想做的只是阅读一行,你可以尝试以下方法:
char buffer[1024];
fgets(buffer, 1024, stdin);
答案 3 :(得分:0)
以下是您正在寻找的代码,
#include <stdio.h>
int main()
{
char str[5][10];
printf("enter the strings...\n");
for(int i =0; i < 5; i++)
scanf("%s", str[i]);
printf("All strings are...\n");
for(int j =0; j < 5; j++)
printf("%s\n", str[j]);
}