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.
You can do looping part this way
int c;
while((c = getchar()) != '\n' && c != EOF)
{
printf("%c", c);
}
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With