我有一个文本文件,每行有两个单词,我想读取它并将每行的第一个单词保存在第一个[numberoflinesinfile][maxcharacterperword]类型的表中,第二个类似表中的一个。其中表的每个条目都是一个字符。
最佳答案
一个非常简单的解决方案:
#include <stdio.h>
#include <string.h>
#define FILE_NAME "myFile.txt"
int main () {
// Open file for reading:
FILE *file;
file = fopen(FILE_NAME, "r");
// Some counters:
int i = 0;
int j;
// Two dimensional arrays:
char first[10][30];
char second[10][30];
// Loop through file:
while ( fscanf(file, "%s", first[i]) != EOF) {
fscanf(file, "%s", second[i]);
i++;
}
for (j = 0 ; j < i ; j++ ) {
printf("first@%d: %s - ", j, first[j] );
printf("second@%d: %s\n", j, second[j] );
}
return 0;
}
输入:
these are
some words
to put
into a
matrix for
some fun
输出:
% ./a.out
first@0: these - second@0: are
first@1: some - second@1: words
first@2: to - second@2: put
first@3: into - second@3: a
first@4: matrix - second@4: for
first@5: some - second@5: fun
关于c - 将文本文件中的单词保存到 c 中的两个表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43531650/