Thread: fgets(buffer,sizeof(buffer),stdin);

  1. #1
    Registered User linuxdude's Avatar
    Join Date
    Mar 2003
    Location
    Louisiana
    Posts
    926

    fgets(buffer,sizeof(buffer),stdin);

    I think this code almost works but for some reason it doesn't wait after the second question? It is suppost to ask you what number you would like to look for in a string then ask you to input the string. The thing is on the second question where it ask you for the string it doesn't wait for an input???
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    void count(int number,char *array,int lenght);
    
    int main(){
            int input,lenght=0,x=0;
            char buffer[200];
            char num[2];
            printf("What single digit integer would you like to look for in a string
    : ");
            fgets(num,sizeof(num),stdin);
            sscanf(num,"%i",&input);
            printf("What is the string you would like to have?\n");
            fgets(buffer,sizeof(buffer),stdin);
            while(buffer[x]!='\n'){
                    ++x;
            }
            count(input,buffer,x);
            return 0;
    }
    void count(int number,char *array,int length){
            auto int count=0; /*counter for while loop*/
            auto int total=0; /*total number of times that number is in the string*/
            while(1){
                    if(array[count]=='\n'){
                            printf("The number apeared %i times\n",total);
                            exit(0);
                    }
                    if(array[count]==number){
                            total+=1;
                            ++count;
                    }
                    else{
                            ++count;
                    }
            }
    }

  2. #2
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    >The thing is on the second question where it ask you for the string it doesn't wait for an input???

    You have 'num' declared as 2 characters long, fgets reads sizeof(num) - 1 characters (1, in this case), so the '\n' may be left in the input stream -- this satisfies the subsequent fgets call.

    Add room for the '\n' in 'num'; or flush the input buffer.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  3. #3
    Registered User linuxdude's Avatar
    Join Date
    Mar 2003
    Location
    Louisiana
    Posts
    926
    thanx that took like twenty minutes for me to get that. :-)

Popular pages Recent additions subscribe to a feed