user14199118
user14199118

Reputation:

How to take the first and last name as one and print in file?

In this code, I am facing a problem that is whenever I try to enter the first and last name, it only prints the first name in the file. But I want to print the last name also. The space between the two words should not be removed. Instead first and last should be considered as one.

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

int main() {
    FILE *fp = fopen("new.csv", "w");
    char name[50];

    printf("Enter your name: ");
    scanf("%s", name);
    fprintf(fp, "%s", name);

    fclose(fp);

    return 0;
}

Upvotes: 2

Views: 1738

Answers (1)

fcdt
fcdt

Reputation: 2493

If you use %s, fscanf read until a whitespace character appear, stopping after the first name.

If there's nothing else at the line e.g. before the user presses Enter, you could use fgets to read in the whole line. The parameters there are the file stream, a pointer to the character array and it's size:

char name[50];
fgets(stdin, name, sizeof(name));

If you still want to use scanf, you could also use %[^\n] instead of %s as mentioned here:

char name[50];
scanf("%49[^\n]", name);

To prevent buffer overflow, you should use scanf only with the buffers size minus one written directly after % (defining maximum field width).

If there's other data in the line after first and last name, you could read them in separately and put them together afterwards:

#include <stdio.h>

int main() {
        char firstName[50];
        char lastName[50];
        scanf("%49s %49s", firstName, lastName);

        char name[50];
        snprintf(name, sizeof(name), "%s %s", firstName, lastName);

        printf("%s\n", name);
}

Upvotes: 1

Related Questions