Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through user input with getchar

I have written a small script to detect the full value from the user input with the getchar() function in C. As getchar() only returns the first character i tried to loop through it... The code I have tried myself is:

#include <stdio.h>

int main()
{
    char a = getchar();
    int b = strlen(a);

    for(i=0; i<b; i++) {
        printf("%c", a[i]);
    }
    return 0;
}

But this code does not give me the full value of the user input.

like image 442
mysql lover Avatar asked Sep 16 '25 08:09

mysql lover


2 Answers

You can do looping part this way

int c;
while((c = getchar()) != '\n' && c != EOF)
{
    printf("%c", c);
}
like image 184
vinayawsm Avatar answered Sep 19 '25 05:09

vinayawsm


getchar() returns int, not char. And it only returns one char per iteration. It returns, however EOF once input terminates.

You do not check for EOF (you actually cannot detect that instantly when getchar() to char).

a is a char, not an array, neither a string, you cannot apply strlen() to it.

strlen() returns size_t, which is unsigned.

Enable most warnings, your compiler wants to help you.

Sidenote: char can be signed or unsigned.

Read a C book! Your code is soo broken and you confused multiple basic concepts. - no offense!

For a starter, try this one:

#include <stdio.h>

int main(void)
{
    int ch;

    while ( 1 ) {

        ch = getchar();
    x:  if ( ch == EOF )     // done if input terminated
            break;

        printf("%c", ch);    // %c takes an int-argument!
    }

    return 0;
}

If you want to terminate on other strings, too, #include <string.h> and replace line x: by:

if ( ch == EOF || strchr("\n\r\33", ch) )

That will terminate if ch is one of the chars listed in the string literal (here: newline, return, ESCape). However, it will also match ther terminating '\0' (not sure if you can enter that anyway).

Storing that into an array is shown in good C books (at least you will learn how to do it yourself).

like image 35
too honest for this site Avatar answered Sep 19 '25 05:09

too honest for this site