Search code examples
cfor-loopgetcharputchar

Getting a character at a time with loop_in_C


I was reading the C Language book and i stuck on following code... As i have shown the C codes i am using the for() loop to get the char in.and same way i use for loop to print a char on screen...if the users presses the enter the loop will quit, and the other for() loop which is used to print on the screen will use the value of i variable. But the result on screen is reversed. Can i get your opinion how can i sort it out?

#include <string.h>
#include <stdio.h>
int main()
{
int i;
char msg[25];
printf_s("Type up to 25 characters then press Enter..\n");
for (i = 0; i < 25; i++)
{
    msg[i] = getchar();// Gets a character at a time
    if (msg[i] == '\n'){
        i--;
        break;// quits if users presses the Enter
    }
}putchar('\n');
for (; i >= 0 ; i--)
{
    putchar(msg[i]);// Prints a character at a time 

}putchar('\n');/*There is something wrong because it revers the input */

getchar();
return 0;

Solution

  • After the input, the variable i holds the exact number of characters in msg. That's why there is a i-- statement, so that when you enter ab<enter> you'll have i==2 not i==3.

    The second loop counts backwards to 0, which isn't what you want. You'll want to count from 0 up to i instead. Now you can't count up to i using i. You need two variables: one to keep the maximum, and one to do the actual counting.

    I'll leave it up to you to decide how to do it exactly, because that's part of the learning.