繁体   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