You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将文件中的字符串复制到二维字符变量中?附C语言代码片段

Hey there! Let's walk through how to finish your implementation of reading strings from a file into a 2D character array, building on the code you've already started.

Step 1: Complete Word Count and Max String Length Calculation

First, you need to finish counting the total number of words and the longest word length in the file. Here's how to fill in that missing logic:

// CHECK WORDS COUNT AND MAX STRING LENGTH
char chr;
int word_count = 0;
int chrcount = 0;
int max_chrcount = 0;
int in_word = 0; // Flag to track if we're inside a word

while ((chr = fgetc(fp)) != EOF) {
    if (chr == ' ' || chr == '\n' || chr == '\t') {
        if (in_word) {
            // End of a word
            word_count++;
            if (chrcount > max_chrcount) {
                max_chrcount = chrcount;
            }
            chrcount = 0;
            in_word = 0;
        }
    } else {
        // Part of a word
        chrcount++;
        in_word = 1;
    }
}
// Don't forget the last word if file doesn't end with whitespace
if (in_word) {
    word_count++;
    if (chrcount > max_chrcount) {
        max_chrcount = chrcount;
    }
}

This code tracks when we enter/exit a word (using whitespace as delimiters), counts each word, and keeps track of the longest word's length.

Step 2: Allocate Memory for the 2D Array

Now that we know how many words we have and the longest word length, we can allocate a 2D character array to store them. We'll use dynamic allocation for flexibility:

// Allocate array of pointers (one per word)
char **words = malloc(word_count * sizeof(char *));
if (words == NULL) {
    printf("Memory allocation failed!\n");
    fclose(fp);
    exit(1);
}

// Allocate memory for each word (plus 1 for null terminator)
for (int i = 0; i < word_count; i++) {
    words[i] = malloc((max_chrcount + 1) * sizeof(char));
    if (words[i] == NULL) {
        printf("Memory allocation failed!\n");
        // Clean up already allocated memory
        for (int j = 0; j < i; j++) {
            free(words[j]);
        }
        free(words);
        fclose(fp);
        exit(1);
    }
}
Step 3: Read Words into the Array and Convert to Lowercase

We need to reset the file pointer to the start of the file, then read each word one by one, convert it to lowercase, and store it in our array:

rewind(fp); // Reset file pointer to start
int index = 0;
char temp_word[max_chrcount + 1]; // Temporary buffer for each word

while (fscanf(fp, "%s", temp_word) != EOF && index < word_count) {
    lower_string(temp_word); // Convert to lowercase
    strcpy(words[index], temp_word); // Copy to our 2D array
    index++;
}
Step 4: Use the Array (Example)

To verify everything works, you can print out all the words:

printf("Words from file (lowercase):\n");
for (int i = 0; i < word_count; i++) {
    printf("%s\n", words[i]);
}
Step 5: Clean Up Memory

Don't forget to free the allocated memory and close the file to avoid leaks:

// Free each word's memory
for (int i = 0; i < word_count; i++) {
    free(words[i]);
}
// Free the array of pointers
free(words);
fclose(fp);
Full Complete Code

Putting it all together, here's the full working code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void lower_string(char s[]) {
    int c = 0;
    while (s[c] != '\0') {
        if (s[c] >= 'A' && s[c] <= 'Z') {
            s[c] = s[c] + 32;
        }
        c++;
    }
}

int main(int argc, char *argv[]) {
    if (argc < 2) {
        printf("Usage : WI_11SI2_12S17048.exe [nama file].txt \n");
        exit(0);
    }
    const char *filename = argv[1];
    FILE *fp = fopen(filename, "r");
    if (fp == NULL) {
        printf("file doesn't exist.\n");
        exit(1);
    }

    // CHECK WORDS COUNT AND MAX STRING LENGTH
    char chr;
    int word_count = 0;
    int chrcount = 0;
    int max_chrcount = 0;
    int in_word = 0;

    while ((chr = fgetc(fp)) != EOF) {
        if (chr == ' ' || chr == '\n' || chr == '\t') {
            if (in_word) {
                word_count++;
                if (chrcount > max_chrcount) {
                    max_chrcount = chrcount;
                }
                chrcount = 0;
                in_word = 0;
            }
        } else {
            chrcount++;
            in_word = 1;
        }
    }
    if (in_word) {
        word_count++;
        if (chrcount > max_chrcount) {
            max_chrcount = chrcount;
        }
    }

    // Allocate 2D array
    char **words = malloc(word_count * sizeof(char *));
    if (words == NULL) {
        printf("Memory allocation failed!\n");
        fclose(fp);
        exit(1);
    }

    for (int i = 0; i < word_count; i++) {
        words[i] = malloc((max_chrcount + 1) * sizeof(char));
        if (words[i] == NULL) {
            printf("Memory allocation failed!\n");
            for (int j = 0; j < i; j++) {
                free(words[j]);
            }
            free(words);
            fclose(fp);
            exit(1);
        }
    }

    // Read words into array
    rewind(fp);
    int index = 0;
    char temp_word[max_chrcount + 1];

    while (fscanf(fp, "%s", temp_word) != EOF && index < word_count) {
        lower_string(temp_word);
        strcpy(words[index], temp_word);
        index++;
    }

    // Example: Print all words
    printf("Words from file (lowercase):\n");
    for (int i = 0; i < word_count; i++) {
        printf("%s\n", words[i]);
    }

    // Cleanup
    for (int i = 0; i < word_count; i++) {
        free(words[i]);
    }
    free(words);
    fclose(fp);

    return 0;
}
Key Notes
  • We use fscanf("%s") here which splits words on whitespace—if you need to handle words with apostrophes or hyphens, you'd need a more custom parsing logic.
  • Always check for malloc failures to avoid crashes from null pointers.
  • Don't skip cleaning up memory and closing the file—this prevents memory leaks and resource issues.

内容的提问来源于stack exchange,提问作者Learner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:04:18