#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2013
    Posts
    2
    Rep Power
    0

    Want a way to read strings with spaces using the gcc compiler


    I'm having a weird problem

    i'm trying to read a string from a console with scanf()

    like this

    scanf("%[^\n]",string1);

    but it doesnt read anything. it just skips the entire scanf.

    I'm trying it in gcc compiler

    I just want to know of a way to read strings with spaces using the gcc compiler Please give me a simple solution. Please don't confuse with buffers and stuff
    Thank you in advance
  2. #2
  3. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2013
    Location
    India
    Posts
    95
    Rep Power
    4
    there should be another scanf before this one.
    due to that scanf of there \n in present in buffer so it takes it.

    solve this problem use separator before % in ur scanf

    Code:
    scanf(" %[^\n]",string1);
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2013
    Posts
    109
    Rep Power
    3
    Also:
    Code:
    char c;
    
    scanf("%s", string);
    scanf("%c", &c); <---to "absorb" the newline character
    I do it so he doesn`t jump over after scanning the string.

    It works.
  6. #4
  7. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,162
    Rep Power
    2222
    Originally Posted by Proff
    I'm having a weird problem

    i'm trying to read a string from a console with scanf()

    like this

    scanf("%[^\n]",string1);

    but it doesnt read anything. it just skips the entire scanf.

    I'm trying it in gcc compiler

    I just want to know of a way to read strings with spaces using the gcc compiler Please give me a simple solution. Please don't confuse with buffers and stuff
    Thank you in advance
    What you're describing works for us. In order to find out why it doesn't seem to work for you, we would need to see what you are actually doing.

    Show us the code that "doesn't work". A shortened program that still exhibits the problem would do as well. Also tell us exactly what you input to get those results.
  8. #5
  9. Contributing User

    Join Date
    Aug 2003
    Location
    UK
    Posts
    5,110
    Rep Power
    1803
    I suggest that you use a more appropriate (and safer) function than scanf() for this:
    Code:
    char string1[256] ; // or whatever size you need
    fgets( string1, sizeof(string1), stdin ) ;
  10. #6
  11. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2013
    Posts
    2
    Rep Power
    0
    Thank you. It works. You saved my day eramit2010 :cool:

IMN logo majestic logo threadwatch logo seochat tools logo