1

I'm with a little problem while doing an excercise to learn C. The problem is: I need to read a string from the user, but if he types just a space, I need to print a space. That's okay in theory. But, when I type the space while the program is running, it doesn't understand it as a string and it keeps waiting for me to type other things.

I'm using the scanf("%[^\n]", string_name_here);

I appreciate your help, and have a nice day! o/ And sorry for my bad english, I hope you can understand this :)

Ramon Machado
  • 15
  • 1
  • 6

1 Answers1

1

Using char *fgets(char *str, int n, FILE *stream) will make your day.

According to man :

fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte ('\0') is stored after the last character in the buffer.

Example program

#include <stdio.h>
#define MAXSTR 21

int main(void)
{
char my_str[MAXSTR] = {'\0'};

fgets(my_str, MAXSTR, stdin);

return 0;
}

Input :

Claudio Cortese

Output :

Claudio Cortese

Claudio Cortese
  • 1,372
  • 2
  • 10
  • 21