Reading two long sentences with scanf

I want to read two long sentences from input using scanf()which are in two new lines.

The code:

int main() {
    char a[100], b[100];
    scanf("%[^\n]s", a);
    scanf("%[^\n]s", b);
    printf("%s\n%s", a, b);
}

Input:

she is beautiful
That is a flower

Conclusion:

she is beautiful

The second input is not read by the operator scanf().

How to fix it?

+4
source share
3 answers

You can use fgets. And that might work for you.

#include <stdio.h>
#include <stdint.h>

int main() {
    char a[100], b[100];

    if (fgets(a, sizeof a, stdin) == NULL) {
        puts("fgets error");
        return -1;
    }

    if (fgets(b, sizeof b, stdin) == NULL) {   //Read blank lines 
        puts("fgets error");
        return -1;
    }

    if (fgets(b, sizeof b, stdin) == NULL) {
        puts("fgets error");
        return -1;
    }

    printf("%s\n%s", a, b);

    return 0;
}
+4
source

For this you need the correct answer. If you insist on using scanf(), there will be only one line of format, which will be safe and do what you want:

int main() {
    char a[100] = "";
    char b[100] = "";
    scanf("%99[^\n]%*c", a);
    scanf("%99[^\n]%*c", b);
    printf("%s\n%s", a, b);
}

[^\n]s, , [^\n] , -, . , s.

- 99. 99 - 0, 100 , . , 99 , .

- %*c: %c , , %[^\n]. , . *, .


, fgets(), , :

int main() {
    char a[100] = "";
    char b[100] = "";
    fgets(a, 100, stdin);
    fgets(b, 100, stdin);

    // if needed, strip newlines, e.g. like this:
    size_t n = strlen(a);
    if (n && a[n-1] == '\n') a[--n] = 0;
    n = strlen(b);
    if (n && b[n-1] == '\n') b[--n] = 0;


    printf("%s\n%s", a, b);
}
+4

int main(){

    char a[100];

    while (scanf("%[^\n]%*c", a)==1) {
     printf("%s\n",a); 
    }
    return 0;
  }
-1

Source: https://habr.com/ru/post/1678687/


All Articles