0

I'm having issues trying to read a white space character in C. What I want to do is read user input when asking for a first and last name.

So for example, I prompt the user to enter their name, they type in something like "Peter Smith". With that info, I want to write it to a file.

When it writes it to a file, the file only reads the last name "Smith". How can I read the whole string?

Here's how I asked:

printf("\nPlease enter your first and last name:  \n");
scanf("%[^\n]", name);
fgets(name, sizeof(name), stdin);
3
  • You could do strchr. cplusplus.com/reference/cstring/strchr then once you find the white space maybe store it in a variable Commented Jun 23, 2014 at 5:13
  • Read again the man page for scanf. Perhaps %s or even %s %s would be more appropriate. Commented Jun 23, 2014 at 5:14
  • 3
    This use of scanf worked for me. What is the fgets part for, though? Maybe the problem is in another part of your program. Commented Jun 23, 2014 at 5:16

2 Answers 2

2

I don't think your problem lies in the snippet you posted. Here's an example program I wrote on my Linux system to try and pinpoint the issue:

#include <stdio.h>

int main()
{
    char name[128];
    int  num_scans = 0;
    FILE *out = fopen("name.txt", "w");

    if(out == NULL)
    {
        printf("Failed to open file for write.\n");
        return 1;
    }   

    printf("\nPlease enter your first and last name:  \n");
    num_scans = scanf("%127[^\n]", name);

    if(num_scans < 1)
    {
        printf("Error reading name.\n");
        return 2;
    }

    fprintf(out, "%s\n", name);

    fclose(out);

    return 0;
}

This appeared to work for me:

$cat name.txt
Peter Smith

If you post the code you used to write the name to a file, that might reveal the source of the error.

Sign up to request clarification or add additional context in comments.

1 Comment

It would be safer to use "%127[^\n]" in the scanf() format. You should also check the return value from scanf(), of course. And trailing blanks before a newline are almost invariably unnecessary (though that's copied from the question).
2

The code is working correctly. The fgets call replaces the value you read for the first name.

You should stick to one scheme of input. When you switch between input paradigms "strange" things happen. (Technically they are exactly what is supposed to happen, but typical users tend to not be too precise about exactly how each function works, and what state the input stream is left in.)

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.