Unexpected result with fgets

int main(int argc, char** argv) { //Local Declaration char last_name[20]; char first_name[20]; char phone_number[20]; char address[30]; //Statement printf("Enter your last name: "); fgets(last_name, 20, stdin); printf("Enter your first name: "); fgets(first_name, 20, stdin); printf("Enter your phone number: "); fgets(phone_number, 20, stdin); printf("Enter your address: "); fgets(address, 30, stdin); printf("=====Address book=====\n"); printf("Name: %s%s\n", first_name, last_name); printf("Phone Number: %s\n", phone_number); printf("Address: %s\n", address); return (EXIT_SUCCESS); } 

The result does not work out, as I expected ... I meant that the first name and surname are on the same line (for example, Mark Zuckerberg). But it looks like this:

Mark

Zuckerberg

What is wrong here? Why is there a new line between them?

+4
source share
3 answers

See manual page

Quote:

fgets () reads no more than one character of size from the stream and saves them to the buffer pointed to by s. Reading stops after EOF or a new line. If a new line is read, it is saved in the buffer. The final null byte (aq \ 0aq) is stored after the last character in the buffer.

So the line read by fgets includes the newline character at the end. You will need to remove it.

EDIT

To remove the end of the line (and enable DOS), do

 int end = strlen(first_name) - 1; if (end >= 0 && '\n' == first_name[end]) { first_name[end--] = 0; if (end >= 0 && '\r' == first_name[end]) first_name[end] = 0; } 
+4
source

As suggested by Ed, see the manual, an easy way to replace '\n' with ' ' (simple space):

 first_name[strlen(first_name) - 1] = ' '; 

strlen uses string.h , remember to enable it

+1
source

fgets() will save '\ n' in the first_name variable when you press enter after you type Mark, so the line stored in first_name will be "Mark \ n", printf() will do its job and print the character new line.

Another good alternative is to use fscanf()

 fscanf (stdin, "%s", first_name); 

EDIT:

Check fscanf() errors.

 char str[50]; int bytes = -1; fscanf (stdin, "%s%n",str,&bytes); if(bytes == -1) perror("\nIncomplete Bytes Parsed\n"); 
0
source

All Articles