[英]Creating an array of strings through user input in c?
I'm new to C so some clarification would be very helpful! 我是C的新手,所以进行澄清将非常有帮助! I'm trying to use a scanner to ask my program for a series of words which I will store..what I have so far is, 我正在尝试使用扫描仪向程序询问要存储的一系列单词。.到目前为止,
char[]listOfWords[9999]; //creates a large array of characters
scanf("%s", listOfWords); //stores inputs into listOfWords
with this, I can access the first word easily, but it comes to a matter of accessing the second, and third words..any suggestion? 这样,我可以轻松访问第一个单词,但是涉及访问第二个和第三个单词的问题。有什么建议吗? For example, how my input was 例如,我的输入是
Hello how are you guys
I can access "Hello" no problem, but how would I call "how" and "are" 我可以访问“ Hello”没问题,但是我怎么称呼“ how”和“ are”
This - char[]listOfWords[9999];
这char[]listOfWords[9999];
is not a valid syntax to declare array. 不是声明数组的有效语法。
You simply need to declare an array - 您只需要声明一个数组-
char s[100];
fgets(s,100,stdin); // take input and store it in s
And using strtok
or sscanf
you can extract separate words in different arrays . 使用strtok
或sscanf
可以提取不同数组中的单独单词。
Or you can use a 2-d array - 或者您可以使用二维数组-
char s[100][100];
So if string stored in it is - Hello how are you guys
所以如果字符串存储在其中-大家Hello how are you guys
then by s[0]
you will get Hello
, s[1]
will give how
and similarly , other words in string. 然后通过s[0]
您将得到Hello
, s[1]
将给出how
和类似的字符串中的其他单词。
Scanf() only accepts input for a single word.(not after space.) Scanf()仅接受单个单词的输入(不包含空格)。
To enter multiple words, you can use gets(string) or scanf("%[^\\n]", string). 要输入多个单词,可以使用gets(string)或scanf(“%[^ \\ n]”,string)。
Is your problem to read multiple words? 您阅读多个单词是否有问题? Or just reading a full line? 还是只是阅读整行? Also the declaration char[]listOfWords[9999]
is wrong. 另外,声明char[]listOfWords[9999]
是错误的。 If you all you want to do is read a line, you can try the following: 如果您只想阅读一行,可以尝试以下操作:
char buffer[1024];
fgets(buffer, 1024, stdin);
Here is a code what you are looking fore, 这是您正在寻找的代码,
#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]); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.