Loop through user input with getchar

15.6k views Asked by At

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.

5

There are 5 answers

0
Sourav Ghosh On
  • Point 1: In your code, a is not of array type. you cannot use array subscript operator on that.

  • Point 2: In your code, strlen(a); is wrong. strlen() calculates the length of a string, i.e, a null terminated char array. You need to pass a pointer to a string to strlen().

  • Point 3: getchar() does not loop for itself. You need to put getchar() inside a loop to keep on reading the input.

  • Point 4: getchar() retruns an int. You should change the variable type accordingly.

  • Point 5: The recommended signature of main() is int main(void).

Keeping the above points in mind,we can write a pesudo-code, which will look something like

#include <stdio.h>
#define MAX 10

int main(void)                        // nice signature. :-)
{
    char arr[MAX]  = {0};            //to store the input
    int ret = 0;

    for(int i=0; i<MAX; i++)      //don't want to overrrun array
    {
      if ( (ret = getchar())!= EOF)  //yes, getchar() returns int
      {
            arr[i] = ret;
            printf("%c", arr[i]);
      }
      else
           ;//error handling
    }
    return 0;
}

See here LIVE DEMO

3
vinayawsm On

You can do looping part this way

int c;
while((c = getchar()) != '\n' && c != EOF)
{
    printf("%c", c);
}
0
too honest for this site On

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).

2
cip On

getchar() : get a char (one character) not a string like you want

use fgets() : get a string or gets()(Not recommended) or scanf() (Not recommended)

but first you need to allocate the size of the string : char S[50] or use a malloc ( #include<stdlib.h> ) :

char *S;
S=(char*)malloc(50);
0
Basile Starynkevitch On

It looks like you want to read a line (your question mentions a "full value" but you don't explain what that means).

You might simply use fgets for that purpose, with the limitation that you have to provide a fixed size line buffer (and handle - or ignore - the case when a line is larger than the buffer). So you would code

char linebuf[80];
memset (linebuf, 0, sizeof(linbuf)); // clear the buffer
char* lp = fgets(linebuf, sizeof(linebuf), stdin);
if (!lp) { 
  // handle end-of-file or error
}
else if (!strchr(lp, '\n')) {
  /// too short linebuf
}

If you are on a POSIX system (e.g. Linux or MacOSX), you could use getline (which dynamically allocates a buffer). If you want some line edition facility on Linux, consider also readline(3)

Avoid as a plague the obsolete gets

Once you have read a line into some buffer, you can parse it (e.g. using manual parsing, or sscanf -notice the useful %n conversion specification, and test the result count of sscanf-, or strtol(3) -notice that it can give you the ending pointer- etc...).