0

I tried to read the two string through scanf, but only first string able to read. Second scanf is not able to read the string and once control is going to second printf, getting some garbage values.

code:
#include<stdio.h>
#include<string.h>
int main(){

        char string1[20], string2[20];

        printf("Enter the first string :");
        scanf("%[^\n]s", string1);

        printf("Enter the second string:");
        scanf("%[^\n]s", string2);

        printf("First string  = %s\n", string1);
        printf("Second string = %s\n", string2);
        return 0;
}


output:

$ ./a.out 
Enter the first string :c programming
Enter the second string:First string  = c programming
Second string = �@
$
Deepak Singh
  • 1,019
  • 2
  • 11
  • 15
  • What's `"%[^\n]s"`??? How did you build this format and why? What was your reasoning behind it? – AnT Oct 25 '17 at 16:56
  • @xin after adding one space in the second scanf, able to read the second string. its working fine. But why need to add one extra space? – Deepak Singh Oct 25 '17 at 17:00

0 Answers0