c - 将文本文件中的单词保存到 c 中的两个表中

标签 c file

我有一个文本文件,每行有两个单词,我想读取它并将每行的第一个单词保存在第一个[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/

相关文章:

C - 如何获取 Char 中的 4 个最低有效位

c - 函数检查短整型算法

iphone - 更改 Xcode 文件模板中的大小写?

带有文件而不是用户输入的 C++ cin

c# - 在 C# 中运行仍处于打开状态的 exe 文件

c - 如何在函数声明语句中使用二维数组?

C 语言 - 在情况下,除了数字之外,我可以使用字符作为开关吗?

c++ - 缺少大小的数组与指针

java - 拒绝访问 - 无法在特定目录中创建文件

file - 在 Electron 中保存用户数据的正确方法