简体   繁体   中英

Reading strings into 2 dimensional array in C

I want to read a number of strings from a text file (standard input) to a 2 dimensional array using getchar() . please ignore the magic number in the code.

#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;
}

you need to use one more getchar() in inner while loop.

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

And need to make variable i again 0 once this string[j][i] = '\\0'; is done.

Also this

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

is wrong. It should be

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

Sample code

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM