reading strings with spaces using sscanf

This is a discussion on reading strings with spaces using sscanf within the C Programming forums, part of the General Programming Boards category; Hi I'm trying to find a way to use sscanf to read a string that can include an unknown number ...

  1. #1
    Registered User
    Join Date
    Apr 2008
    Posts
    101

    Question reading strings with spaces using sscanf

    Hi

    I'm trying to find a way to use sscanf to read a string that can include an unknown number of spaces.

    I'm using so far
    Code:
    char in[1024];
    int r = 0;
    while ( r == 0){
    	printf("Insira o nome do restaurante a guardar:\n");
    	fgets(in, 1024, stdin);
    	r = sscanf(in, "%s\n", restaurante->nome);
    }
    Someone can please tell what should I change? I'm just getting the first word since it stops at white spaces.

  2. #2
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,048
    Well, you could just use the in array. You can strip the newline like so:
    Code:
    char *p;
    if((p = strchr(in, '\n'))) *p = 0;
    Or you could use this.
    Code:
    #include <stdio.h>
    
    int main() {
        char buffer[10];
    
        printf("Enter a string: ");
        scanf("&#37;9[^\n]", buffer);
        puts(buffer);
    
        return 0;
    }
    Personally, I'd just use the result of fgets() . . . .
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  3. #3
    Registered User
    Join Date
    Apr 2008
    Posts
    101

    Thanks

    Thank you very much I didn't know about strchr.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help with reading strings and opening files PLEASE
    By green2black in forum C Programming
    Replies: 8
    Last Post: 11-17-2008, 05:46 PM
  2. reading strings with spaces
    By dezz101 in forum C Programming
    Replies: 10
    Last Post: 10-29-2008, 07:02 AM
  3. Reading spaces from file
    By arya6000 in forum C Programming
    Replies: 2
    Last Post: 12-08-2007, 12:43 AM
  4. reading from a file + list of strings
    By stewie1986 in forum C Programming
    Replies: 2
    Last Post: 12-06-2007, 11:59 PM
  5. Question on malloc() and reading strings
    By rockysfr in forum C Programming
    Replies: 2
    Last Post: 09-04-2005, 07:37 PM

Tags for this Thread


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21