allow spaces with scanf

Go To Last Post
5 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Hi - I am working on a SAMD21 project. I'm using the Stardard I/O module for receiving input from the user via USART. How do allow a space to be entered with scanf? I've tried fgets, but that caused the program to crash.

 

char input[32];
printf("\n\rEnter Description: ");			
scanf("%s", input);		

 

"When all else fails, read the directions"

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Life is generally easier if you receive a complete sentence e.g. up to the newline (or buffersize)
Then use sscanf() on the string if you are a masochist. Or process it yourself.
.
David.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

fgets seems appropriate if you are not actually parsing anything. Where is the crash with fgets? Is there really a problem with a simple main loop like below?

    while (1) {	
        char input[32];
        printf("\n\rEnter Description: ");
        fgets(input, sizeof(input), stdin);
        printf("Description: %s", input);
    }

/Lars

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Lajon wrote:
Where is the crash with fgets?

 

There was no crash. I was mistaken. What was happening was fgets waits for the buffer to be full (32) before finishing. I need to finish fgets when the user hits enter (carriage return). I was able to right something myself using scanf but it doesnt seem elegant.

 

 

"When all else fails, read the directions"

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

fgets should return when a newline is received, maybe there is a mismatch with the sender (terminal program or whatever) sending only CR ('\r' 0xD) while fgets need LF ('\n' 0xA).

/Lars