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?

4
  • scanf("%[^\n]s",s1); --> scanf("%[^\n]%*c", s1); Commented Dec 10, 2015 at 6:47
  • Possible duplicate of how to take input of two string? Commented Dec 10, 2015 at 6: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. Commented Dec 10, 2015 at 7: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. Commented Dec 10, 2015 at 7:34

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.