我有一个简单的问题:让用户从键盘输入一些单词,每行一个单词,直到出现“。” (句号)输入然后打印出结果,例如:
Enter a word: word1
Enter a word: word2
Enter a word: .
You have entered 2 word(s):
word1
word2
好的,我试试,但是当我运行它时说文件在让我输入第一个单词后停止工作
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>
int main ()
{
char *word[50]; //each word has maximum 49 character
int i=0, number_of_word;
do
{
printf ("Enter a word: ");
scanf("%s", &word[i]);
i++;
}
while (word[i][0]!='.');
number_of_word =i;
printf ("You entered %d word(s):\n", number_of_word);
for (i=0; i<number_of_word; i++)
{
printf("%s\n", &word[i]);
}
return 0;
}
-------------------------------------------------- ---------------------
编辑1:
好的,我试试这个,它有效,但我仍在寻找最好的方法来声明一个未知大小的字符串数组,因为我不知道用户可以输入多少个单词,也不知道每个单词有多少个字母,在 C++ 中它可能调用动态分配数组,我不知道如何在 C 中做到这一点
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>
int main ()
{
char word[20][50]; //array has maximum 20 words, each word maximum 50 character
int i=0, number_of_word;
do
{
printf ("Enter a word: ");
scanf("%s", word[i]);
i++;
}
while (word[i-1][0]!='.');
number_of_word =i-1;
printf ("You entered %d word(s):\n", number_of_word);
for (i=0; i<number_of_word; i++)
{
printf("Word %d is %s\n", i, word[i]);
}
return 0;
}