简体   繁体   中英

loop terminating early in C

Encountered a situation in my problem where I had to input multiple strings as input. Now, my logic was to create a 2d array where (example)

Input:
ABD
okay

would be stored as

[['A','b','D'],['o','k','a','y']]

ideally, it should terminate when I input an empty string.

but my code(below) only takes first input and terminates.

    char str[100];
    char stringArray[50][100];
    int k,m,count=0,i=0,j=0;
    do {
        scanf("%[^\n]",&str);
        k=strlen(str);
        for(m=0;m<k;m++){
            stringArray[count][m]=str[m];
        }
        count++;
    }
    while (str[0] != '\0');

For starters the second argument of the call of scanf

scanf("%[^\n]",&str);

has the incorrect type char ( * )[100] instead of char * .

You need to write

scanf("%[^\n]",str);

However the new line character '\\n' stays in the input buffer after this call.

At least you need to read it for example like

scanf( "%*c" );

Though it will be simpler to use the function fgets instead of scanf.

For example

fgets( str, sizeof( str ), stdin );

And instead of the do-while loop it will be better to use a while loop.

For example

while ( fgets( str, sizeof( str ), stdin ) != NULL && str[0] != '\n' )
{
    //...
} 

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