user3766141
user3766141

Reputation: 1

Reading whitespace when asking user input C

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);

Upvotes: 0

Views: 70

Answers (2)

Dwayne Towell
Dwayne Towell

Reputation: 8583

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.)

Upvotes: 2

Austin Mullins
Austin Mullins

Reputation: 7427

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.

Upvotes: 2

Related Questions