Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a string with spaces with sscanf

Tags:

c

string

scanf

For a project I'm trying to read an int and a string from a string. The only problem is sscanf() appears to break reading an %s when it sees a space. Is there anyway to get around this limitation? Here's an example of what I'm trying to do:

#include <stdio.h> #include <stdlib.h>  int main(int argc, char** argv) {     int age;     char* buffer;     buffer = malloc(200 * sizeof(char));     sscanf("19 cool kid", "%d %s", &age, buffer);      printf("%s is %d years old\n", buffer, age);     return 0; } 

What it prints is: cool is 19 years old where I need cool kid is 19 years old. Does anyone know how to fix this?

like image 600
SDLFunTimes Avatar asked May 18 '10 04:05

SDLFunTimes


People also ask

How do you read a string with spaces?

Once the character is equal to New-line ('\n'), ^ (XOR Operator ) gives false to read the string. So we use “%[^\n]s” instead of “%s”. So to get a line of input with space we can go with scanf(“%[^\n]s”,str);

Does sscanf ignore whitespace?

You can't do this work with the sscanf function and a "central" string with an arbitrary number of spaces in it, since the whitespace is also your delimiter for the next field; if that %s matched strings with whitespace, it would "eat" also the 6.

Can scanf read spaces?

Adding a whitespace character in a scanf() function causes it to read elements and ignore all the whitespaces as much as it can and search for a non-whitespace character to proceed. scanf("%d "); scanf(" %d"); scanf("%d\n"); This is different from scanf("%d"); function.


2 Answers

The following line will start reading a number (%d) followed by anything different from tabs or newlines (%[^\t\n]).

sscanf("19 cool kid", "%d %[^\t\n]", &age, buffer); 
like image 137
BrunoLM Avatar answered Oct 07 '22 19:10

BrunoLM


You want the %c conversion specifier, which just reads a sequence of characters without special handling for whitespace.

Note that you need to fill the buffer with zeroes first, because the %c specifier doesn't write a nul-terminator. You also need to specify the number of characters to read (otherwise it defaults to only 1):

memset(buffer, 0, 200); sscanf("19 cool kid", "%d %199c", &age, buffer); 
like image 35
caf Avatar answered Oct 07 '22 17:10

caf