sourcecode
sourcecode

Reputation: 1802

Insert values through getchar

I am unable to insert a value into ptr char array:

int main() {

  char S[MAX_STRING_LENGTH],*str;

  int total,j=0,i=0;
  char ptr[16],c;

    scanf("%d",&total);

      for(i=0;i<total;i++){
          c=getchar();
           do{

           ptr[j]=(char)tolower(c);
           j++;
           c=getchar();
           }while(c!='\n' && j<15 );

           ptr[j]='\0';
           printf("j=%d , %s",j,ptr);
           }

}

The reason for this I know:

I put do-loop exit on '\n' and I'm using enter('\n') itself after inserting value in total. That way it is exiting loop without insertion of value.

How can I correct it?

Upvotes: 0

Views: 191

Answers (3)

yuan
yuan

Reputation: 2534

Because scanf did scan \n in the input stream but it didn't store it in &total . The next time you getchar() it will get it \nwhich cause the do-while only can execute once.
add

getchar();

after scanf.

input stream :

            the next you getchar() will from here
             |
             | 
A A A A A A \n A A A A A A
          ^
          |
  the variable total store string before this        

Upvotes: 2

Vallabh Patade
Vallabh Patade

Reputation: 5110

During scanf you will enter some no(no of characters) say 10 and will hit enter. Now this '\n\ will not be read by scanf and it's there in input stream. During first iteration, getchar() will read this '\n' and will terminate the loop after first iteration. So better put a getchar() after scanf() so as no make inputstream to empty. apart from this,

You haven't put any check beyond array index limit. It maybe the case user keep entering the characters and you endup trying to insert beyond 16 places.

 while(c != '\n' && j < 15);

Will solve your problem.

Upvotes: 0

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70939

What you are doing is kind of unsafe. First of all depending on the operating system you may have to terminate on '\r' not only on '\n'. Second you never check the size of the input to be within 15 symbols. Please note I say 15 symbols because it is usually good practise to leave one cell for the zero terminating character.

If the input does not contain whitespaces(space or tab) I would advice you to use scanf("%s") as it is less error-prone. Also you will eliminate the need for a while loop.

If that is not the case, you should add a check for '\r' as well and also you will have to remove the newline character that you type after the total value. Like so:

scanf("%d", &total);
getchar();

This is needed because otherwise the newline after total will be the first char you read in your while loop and thus you will exit on the first iteration of the cycle.

If you debug your program you will see that this happens.

Upvotes: 2

Related Questions