簡體   English   中英

將字符串讀入C中的二維數組

[英]Reading strings into 2 dimensional array in C

我想使用getchar()從文本文件(標准輸入)讀取多個字符串到二維數組。 請忽略代碼中的幻數。

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

int
main(int argc, char *argv[]) {

    char string[100][20];
    int c, j = 0, i = 0; 

    while ((c = getchar()) != EOF) {    
        while (c != '\n') {
            string[j][i] = c;
            i++;
        }
        string[j][i] = '\0';
        j++;
    }
    printf('string is: %s', string);

    return 0;
}

您需要在內部 while 循環中再使用一個getchar()

while (c != '\n') {
       string[j][i] = c;
       i++;
       c = getchar(); /* this you need here to fetch char until \n encounters */
 }

並且一旦此string[j][i] = '\\0';需要再次使變量i 0 已經完成了。

還有這個

printf('string is: %s', string);

是錯的。 它應該是

printf("string is: %s", string); /* use double quotation instead of single */

示例代碼

int main(int argc, char *argv[]) {

        char string[100][20];
        int c, j = 0, i = 0;

        while ((c = getchar()) != EOF) { /* this loop you need to terminate by pressing CTRL+D(in linux) & CTRL+Z(in windows) */ 
                while (c != '\n') { /* this loop is for 1D array i.e storing char into each 1D array */
                        string[j][i] = c;
                        i++;
                        c = getchar(); /* add this, so that when you press ENTER, inner while loop fails */
                }
                string[j][i] = '\0';
                j++;
                i = 0;/* make it zero again, so that it put char into string[j][0] everytime once 1 line is completed */
        }
        for(int row = 0;row < j;row++) { /* rotate loop j times since string is 
2D array */
        printf("string is: %s", string[row]);
        }

        return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM