-5

EDIT: I think my issue is coming from the compile and linux VM that I am using. Please ignore.

I am new to C and am having trouble accepting string inputs with spaces. I have searched for the answer on this website, but none of the proposed solutions have worked, fgets and scanf both truncate the string as soon as the first space is reached. I have also tried scanf("%99[^\n]", name) and that does not work either.

This is my code:

#include<stdio.h>

int main ()
{
 char name[100];

 printf("What is your name? "); 
 fgets(name, 100, stdin);
 printf("Hello %s. Nice to meet you\n", name);
 return 0;
}

I have also tried scanf, but if the input is john smith, it only outputs john.

Thank you

Maverick
  • 661
  • 1
  • 8
  • 12

1 Answers1

2

Scanf has the habit of truncating your input to match its format. Without any fancy requirements or other tools, you can get your input with fgets from stdin or the like, then use functions like strtok to tokenize your string into what you need (names, surnames etc).

webuster
  • 2,490
  • 18
  • 27