Thread: Help needed

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

    Join Date
    Feb 2013
    Posts
    22
    Rep Power
    0

    Help needed


    Hello everyone. I am having a problem with a small program I am trying to create. Main function of the program is to receive a String and print how many words it contains. For example if I give as input "Hello World" It should return 2. Althought the user can leave more than one space between the words. The problem is that it always returns me 3 as a result.
    Here's the code.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    int main()
    {
        char a[50];
        char *p;
        int flag=1;
        int sum=0;
        
        printf("Give me a string \n");
        scanf("%s",&a);
        p=&a[0];
    
            while(*p!='\0')
            {
                          
                           while(*p!=' ')
                           {
                           
                                       flag=0;
                                       p++;
                           }
                           if(flag==0)
                           {
                                      sum++;
                           }
                           
                                
                           flag=1;
                           p++;
                           
            }
      
        printf("Sum equals to %d", sum);
        system("pause");
    }
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    159
    Rep Power
    19
    Do you realize that scanf() stops processing your string when it encounters a whitespace character? Also using scanf() to retrieve a string, without using the proper width specifier is very dangerous.


    Jim
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    22
    Rep Power
    0
    Originally Posted by jimblumberg
    Do you realize that scanf() stops processing your string when it encounters a whitespace character? Also using scanf() to retrieve a string, without using the proper width specifier is very dangerous.


    Jim
    Thank you for the quick reply Jim. Do you have any suggestions how can I complete the task since scanf is out of the question.
  6. #4
  7. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,854
    Rep Power
    481
    read the data with
    fgets
    [code]Code tags[/code] are essential for python code and Makefiles!

IMN logo majestic logo threadwatch logo seochat tools logo