在C中将字符串读取为二维数组

时间:2018-09-15 09:51:50

标签: c arrays string getchar

我想使用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;
}

1 个答案:

答案 0 :(得分:0)

您需要在内部while循环中再使用一个getchar()

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

完成此i之后,需要再次0创建变量string[j][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;
}