简体   繁体   中英

Scanf(“%[^\n]”) not working with array string inside loop

I've written this code in C. I need to solve a problem and there I'll have to input 5 line string including whitespace. This program will just give me output of all 5 line string including whitespace. By white space I mean on input I can put space before and char or after any char. That's why I've written this code but I can't understand why it's not working.

#include<stdio.h>
int main() {
    char str[5][100];
    for(int i=0;i<5;i++) {
        scanf("%[^n\]",str[i]);
    }
    for(int j=0;j<5;j++) {
        printf("%s\n",str[j]);
    }
    return 0;
}

I tried to use only

scanf("%s",str[i]);

but then it's ignoring all whitespace inside the input and trimming the output. Also I tried to use

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

this time little better but it's ignoring the all white space before any character a example input is like.

    Robin Islam
// output showing
Robin Islam
// should show
    Robin Islam

I just want to make this program to allow whitespace on every I mean output should show the same as input without ignoring space. Someone please help me. Tried lot's of way but don't know how to make it works or how......Help please

Thanks, Robin

scanf is riddled with problems, just search for it here and you'll see. It should be avoided whenever possible.

You're reading whole lines, and there are functions for doing that. fgets and getline . I prefer getline because it handles memory allocation for you, there's no risk of your input overrunning a buffer.

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

int main() {
    char *line = NULL;
    char *lines[5];
    size_t linecap = 0;

    for( int i = 0; i < 5; i++ ) {
        /* Getline will allocate sufficient memory to line.
           It will also reuse line, so... */
        getline(&line, &linecap, stdin);

        /* ...we have to copy the line */
        lines[i] = strdup(line);
    }

    /* line must be freed after calls to getline() are finished */
    free(line);

    for( int i = 0; i < 5; i++ ) {
        printf("%s\n", lines[i]);
    }

    /* Cleaning up all memory is a good habit to get into.
       And it removes clutter from you Valgrind report. */
    for( int i = 0; i < 5; i++ ) {
        free(lines[i]);
    }

    return 0;
}
#include<stdio.h>
#include<stdlib.h>

int main() {

    char str[5][100];
    for(int i=0;i<5;i++) {
        fgets(str[i],100,stdin);
    }
    for(int j=0;j<5;j++) {
        printf("%s\n",str[j]);
    }

    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