1

I am unable to take two inputs strings simultaneously in C on Ubuntu. It shows the wrong output. Simple program:

#include <stdio.h>
main()
{
    char s1[20],char s2[20],printf("\nEnter job:");
    scanf("%[^\n]s",s1);
    printf("Enter hobby:");
    scanf("%[^\n]s",s2);
}

Output:

Enter job:student
Enter hobby:
student

It does not allow the input of a second string. How can I overcome this bug?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
ruchita
  • 13
  • 4
  • `scanf("%[^\n]s",s1);` --> `scanf("%[^\n]%*c", s1);` – BLUEPIXY Dec 10 '15 at 06:47
  • Possible duplicate of [how to take input of two string?](http://stackoverflow.com/questions/23135602/how-to-take-input-of-two-string) – Ken Y-N Dec 10 '15 at 06:51
  • 1
    Note that the code won't compile, even when formatted correctly. You need a semi-colon before the first `printf()`, not a comma. The problem is that there's a newline in the input and your format won't allow the the newline to be read, so it fails. Check the return status of `scanf()`. And read the newline before scanning, or put a space before the `%[^\n]`. Also notice that a scan set is `%[…]`; it is not a modifier for `%s`. – Jonathan Leffler Dec 10 '15 at 07:03
  • `scanf` should be given the maximum number of characters to read and store into `s1` and `s2`, otherwise invalid input will invoke undefined behavior. This kind of bug is a blatant security flaw. – chqrlie Dec 10 '15 at 07:34

1 Answers1

1

If you want to allow embedded spaces, modify the scanf formats this way:

#include <stdio.h>

int main(void) {
    char job[100], hobby[100];
    printf("Enter job:");
    scanf("%99[^\n]%*c", job);
    printf("Enter hobby:");
    scanf("%99[^\n]%*c", hobby);
    printf("%s,%s", job, hobby);
    return 0;
}

But be aware that empty lines will not be accepted by this scanf format. The linefeed will stay in the input stream, the second scanf will fail too and job and/or hobby will have indeterminate contents, letting printf invoke undefined behavior.

Is is much more reliable to use fgets() and strip the '\n'.

#include <stdio.h>
#include <string.h>

int main(void) {
    char job[100], hobby[100];

    printf("Enter job:");
    if (!fgets(job, sizeof job, stdin))
        return 1;
    job[strcspn(job, "\n")] = '\0';

    printf("Enter hobby:");
    if (!fgets(hobby, sizeof hobby, stdin))
        return 1;
    hobby[strcspn(hobby, "\n")] = '\0';

    printf("%s,%s", job, hobby);
    return 0;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189