如何读取整个数组的数组,直到来自文件格式的换行符为:
苹果
葡萄
bananna
我希望每个单词都从文件中存储为数组中的单独值。我怎么能这样做?
全部谢谢
答案 0 :(得分:0)
您可以使用fgets功能,例如
char word[100][100];
int i = 0;
while( fgets( word[i++], 80, file) )
;
答案 1 :(得分:0)
试试这个
char *my_strchr(char * string_ptr, char find)
{
while (*string_ptr != find) {
/* Check for end */
if (*string_ptr == '\0')
return (NULL); /* not found */
++string_ptr;
}
return (string_ptr); /* Found */
}
int words_count(char * string_ptr, char find)
{
int i = 0;
while (*string_ptr != '\0') {
/* Check for end */
if (*string_ptr == find)
++i; /* not found */
++string_ptr;
}
return (i+1); /* Found */
}
int main()
{
char line[80]; /* The input line */
char *first_ptr; /* pointer to the first name */
char *last_ptr; /* pointer to the last name */
// char words[3][80];
char **words;
int cnt;
// fgets(line, sizeof(line), stdin);
static const char filename[] = "C:\\Diginity-Works\\LineReader\\debug\\data.txt";
FILE *file = fopen ( filename, "r" );
while ( fgets ( line, sizeof line, file ) != NULL ) // read a line
{
/* Get rid of trailing newline */
line[strlen(line)-1] = '\0';
cnt = words_count(line, ' ');
// for the "first level"
words = (char **) malloc(cnt * sizeof *words);
// In the second level
for(int i=0;i<cnt;++i)
words[i]=(char*)malloc(80);// i assume that max word length is 80
last_ptr = line; /* last name is at beginning of line */
for(int i=0; i < cnt; ++i){
first_ptr = my_strchr(line, ' '); /* Find space */
/* Check for an error */
if (first_ptr == NULL) {
strcpy(words[i], last_ptr);
break;
}
*first_ptr = '\0'; /* Zero out the slash */
++first_ptr; /* Move to first character of name */
strcpy(words[i], last_ptr);
strcpy(line, first_ptr);
}
for(int i=0; i < cnt; ++i)
printf("%d : %s \n", i, words[i]);
}
return (0);
}