scanf not accepting space as part of string

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • bajajv
    New Member
    • Jun 2007
    • 152

    scanf not accepting space as part of string

    Hi,
    I am writing a program to accept a string from the user. But not able to print the whole sentence. Can get only first word -
    Input - My name is Anthony
    output- My
    How can I print the whole sentence?
    code -
    Code:
    int main()
    {
            char* str;
            str = (char*) malloc (sizeof(char)*256);
            memset (str, 0, (sizeof(char)*256));
            printf("Enter the string\n" );
            scanf("%s", str);
            printf("%s\n", str);
            return 0;
    }
    Last edited by bajajv; Jul 22 '10, 06:02 AM. Reason: question looks incomplete
  • whodgson
    Contributor
    • Jan 2007
    • 542

    #2
    The usual way is to use the getline() function

    Comment

    • Banfa
      Recognized Expert Expert
      • Feb 2006
      • 9067

      #3
      getline() is C++ in C you would use fgets()

      Comment

      • bajajv
        New Member
        • Jun 2007
        • 152

        #4
        Originally posted by Banfa
        getline() is C++ in C you would use fgets()
        Thanks.. its working..

        Is there any way to make scanf accept whole line?

        Comment

        • newb16
          Contributor
          • Jul 2008
          • 687

          #5
          scanf("%[^\n]s",s);

          Comment

          • bajajv
            New Member
            • Jun 2007
            • 152

            #6
            Originally posted by newb16
            scanf("%[^\n]s",s);scanf( "%[^\n]s",s);
            scanf("%[^\n]s",s);

            looks great...

            Comment

            • donbock
              Recognized Expert Top Contributor
              • Mar 2008
              • 2427

              #7
              I think you have an extra "s". This should work:
              scanf("%[^\n]", s);

              By the way, this format string makes use of an inverted scanset. You can google "scanf scan set" for more details.

              Comment

              • Banfa
                Recognized Expert Expert
                • Feb 2006
                • 9067

                #8
                And of course that scanf line does not protect against buffer overrun in which fgets does.

                Comment

                Working...