c - How to copy a sentence into a char array -
i trying copy sentence char array. have tried using scanf("%[^\n]) , scanf("%[^\n]\n within if statement doesn't work. can please me figure out? using c language. works first code not second.
file #1
#include <stdio.h> int main () { char c[10]; printf ("enter text.\n"); scanf("%[^\n]", c); printf ("text:%s", c); return 0; } file #2
#include <stdio.h> #include <string.h> int main(void) { char command[10]; char c[10]; printf("cmd> "); scanf( "%s", command); if (strcmp(command, "new")==0) { printf ("enter text:\n"); scanf("%[^\n]", c); printf ("text:%s\n", c); } return 0; }
put space before %[^\n] so:
#include <stdio.h> #include <string.h> int main(void) { char command[10]; char c[10]; printf("cmd> "); scanf( "%s", command); if (strcmp(command, "new")==0) { printf ("enter text:"); scanf(" %[^\n]", c); // note space printf ("text:%s", c); } return 0; } it should work now. space makes consume whitespace of previous inputs.
here's output when tested without space:
cmd> new enter text:text:@ ------------------ (program exited code: 0) and space:
cmd> new enter text:test text:test ------------------ (program exited code: 0)
Comments
Post a Comment