putc skips an index putchar does not? - c

I have an a method that reads input and prints ascii characters to a file stream.
Originally it didn't need to print to a file so I used putchar and it worked fine
but now that I use putc or fputc it prints every other input.
Example:
input = test
Output = t s
int readFile(char* input,FILE* inputFile)
{
int anyChanges = 1;
int iochar = 0;
int i = 0;
//credit Foster Chapter 2
while (( iochar = getc(inputFile) ) != EOF )
{
//Returns 1 if no changes made, return 0 if any changes have been made.
// printf("\t character --> %c",iochar);
//printf("\nGot to first while loop\n");
if(iochar != '\n')
{
// printf("Got to second loop\n");
int printedColumns =0;
input[i] = iochar;
printf("input array ---> %c\n",input[i]);
i++;
printf("i:%d\n",i);
printf("iochar:%d\n",iochar);
//This if statement checks for normal ascii characters.
//If the output is less than 72 it prints it and increments printedColumns.
if (( ' ' <= iochar ) && ( iochar <= 126 ) )
{
fputc(input[i],inputFile);
}
}
}
}

Here for getc & putc you are using same Stream pointr i.e. inputFile , you want to read and write onto same file ??

did you mean to fputc iochar instead of input[i] (since you already incremented i)?
http://www.cplusplus.com/reference/cstdio/fputc/ states that the position indicator is incremented.

Related

get string in input and print it folded in C

I'm trying to write a program which gets one or more input lines, and if one line is too long, it gets folded at a maximum number of chars. My approach would be to write the input chars in a first array, of a given length. If Maximum length is reached or '\n' as input, i copy the content in a bigger array which will be the final string to print and get the second line in input. Problem is: it doesn't work and I can't figure out why. Thanks for the help
#include <stdio.h>
#define MAXCOL 10
#define FINAL_LENGTH 300
char line[MAXCOL];
char final_string[FINAL_LENGTH];
extern int fnlstr_pos = 0;
int main()
{
int pos, c;
pos = 0;
while(c=getchar() != EOF)
{
line[pos] = c;
if (pos + 1 >= MAXCOL || c == '\n'){
to_printandi(pos);
pos = 0;
}
++pos;
}
printf("%s", final_string);
}
to_printandi(pos)
int pos;
{
int i;
for(i = 0; i <= pos; ++i){
final_string[fnlstr_pos] = line[i];
++fnlstr_pos;
}
if (final_string[fnlstr_pos] != '\n'){
final_string[++fnlstr_pos] = '\n';
}
++fnlstr_pos;
}
There are several problems in the code. Others have already pointed out the bug in the getchar() line.
More variables and more functions and more code only twist one around in knots. If you take some time to think about what you want to achieve, go slowly, you can get your results with much less effort. Less code full of helpful comments, make for better programs.
EDIT
Looking at code with fresh eyes, I realised that the two lines explicitly setting the 'trailing' byte to '\0' were write 0 overtop of bytes already initialised to 0. Have commented out those two lines as they are superfluous.
#include <stdio.h>
int main () {
char buf[ 1024 ] = { 0 }; // buffer initialised
int ch, cnt = 0, ccnt = 0; // input char and counters
while( ( ch = getchar() ) != EOF ) { // get a character
ccnt++; // count this character
buf[ cnt++ ] = (char)ch; // assign this character
// buf[ cnt ] = '\0'; // string always terminated
if( buf[ cnt-1 ] == '\n' ) // user supplied LF?
ccnt = 0; // reset the counter (for width)
else
if( ccnt == 10 ) { // reached max output width?
buf[ cnt++ ] = '\n'; // inject a LF
// buf[ cnt ] = '\0'; // string always terminated
ccnt = 0; // reset the counter (for width)
}
}
puts( buf ); // output the whole shebang
return 0;
}
0123456789abcdefghijklmnop
qrs
tuv
wxyz
^D // end of input
0123456789
abcdefghij
klmnop
qrs
tuv
wxyz
Like the OP code, this does not test for overrunning the buffer. An easy addition left as an exercise for the reader.
EDIT2:
Then again, why have a buffer to overrun?
#include <stdio.h>
void main( void ) {
for( int ch, n = 0; ( ch = getchar() ) != EOF; /**/ )
if( (n = putchar( ch ) == '\n' ? 0 : n + 1) == 10 )
putchar( '\n' ), n = 0;
}
This question is very broad and it would helpful if you said what the problem is but I can see one issue -- you don't null terminate the final_string variable. add
final_string[fnlstr_pos] = '\0';
before the printf.
Maybe that fixes the problem you are having.
For starters this statement
while(c=getchar() != EOF)
is equivalent to
while( c = ( getchar() != EOF ) )
So c is always equal to1 if EOF is not encountered.
You need to write
while( ( c=getchar() ) != EOF)
And you need to append the input sequence with the terminating zero character '\0' tp form a string.
Another problem is these code snippet with for loop
for(i = 0; i <= pos; ++i){
final_string[fnlstr_pos] = line[i];
++fnlstr_pos;
}
As within the loop the variable fnlstr_pos was increased then this if statement
if (final_string[fnlstr_pos] != '\n'){
final_string[++fnlstr_pos] = '\n';
}
invokes undefined behavior because the variable points to a non-initialized element of the array.
The main problem is here:
while(c=getchar() != EOF)
Given the operator precedence, this will result in the same as:
while(c= (getchar() != EOF))
So c will be 1 (true) inside the loop.
Change this to:
while((c=getchar()) != EOF)
This is the main problem. Just as #Hogan suggested, there are other issues such as not null terminating the strings.
As you declare them global, they will be zeroed so you can get away with that though not in the case the user provides a string with maximum length.
Also it would greatly improve the code if you could use string manipulation functions from <string.h> instead of copying byte by byte.

K&R C programming book exercise 1-18

I'm towards solving the exercise, but just half way, I find it so weird and cannot figure it out,
the next is the code snippet, I know it is steps away from finished, but I think it's worth figuring out how come the result is like this!
#define MAXLINE 1000
int my_getline(char line[], int maxline);
int main(){
int len;
char line[MAXLINE];/* current input line */
int j;
while((len = my_getline(line, MAXLINE)) > 0 ){
for (j = 0 ; j <= len-1 && line[j] != ' ' && line[j] != '\t'; j++){
printf("%c", line[j]);
}
}
return 0;
}
int my_getline(char s[], int limit){
int c,i;
for (i = 0 ; i < limit -1 && (c = getchar()) != EOF && c != '\n'; i++)
s[i] = c;
if (c == '\n'){
s[i] = c;
++i;
}
s[i] = '\0';
return i;
}
It will be compiled successfully with cc: cc code.c. But the following result is subtle!
Iit is working for lines without \t and blanks:
hello
hello
but it does not work for the line in the picture:
I typed hel[blank][blank]lo[blank]\n:
Could anyone help me a bit? many thanks!
The problem is that you are stuck because you try to get a full line and process it. It's better to process (and the problems of K&R are mostly this way all) the input char by char. If you don't print characters as you detect spaces, but save them in a buffer, and print them if there's a nontab character when you read one past the accumulated ones, then everything works fine. This is also true for new lines. You should keep the last (nonblank) character (as blanks are eliminated before a new line) read to see if it is a newline... in that case, the new line you have just read is not printed, and so, sequences of two or more newlines are only printed the first. This is a sample complete program that does this:
#include <stdio.h>
#include <stdlib.h>
#define F(_f) __FILE__":%d:%s: "_f, __LINE__, __func__
int main()
{
char buffer[1000];
int bs = 0;
int last_char = '\n', c;
unsigned long
eliminated_spntabs = 0,
eliminated_nl = 0;
while((c = getchar()) != EOF) {
switch(c) {
case '\t': case ' ':
if (bs >= sizeof buffer) {
/* full buffer, cannot fit more blanks/tabs */
fprintf(stderr,
"we can only hold upto %d blanks/tabs in"
" sequence\n", (int)sizeof buffer);
exit(1);
}
/* add to buffer */
buffer[bs++] = c;
break;
default: /* normal char */
/* print intermediate spaces, if any */
if (bs > 0) {
printf("%.*s", bs, buffer);
bs = 0;
}
/* and the read char */
putchar(c);
/* we only update last_char on nonspaces and
* \n's. */
last_char = c;
break;
case '\n':
/* eliminate the accumulated spaces */
if (bs > 0) {
eliminated_spntabs += bs;
/* this trace to stderr to indicate the number of
* spaces/tabs that have been eliminated.
* Erase it when you are happy with the code. */
fprintf(stderr, "<<%d>>", bs);
bs = 0;
}
if (last_char != '\n') {
putchar('\n');
} else {
eliminated_nl++;
}
last_char = '\n';
break;
} /* switch */
} /* while */
fprintf(stderr,
F("Eliminated tabs: %lu\n"),
eliminated_spntabs);
fprintf(stderr,
F("Eliminated newl: %lu\n"),
eliminated_nl);
return 0;
}
The program prints (on stderr to not interfer the normal output) the number of eliminated tabs/spaces surrounded by << and >>. And also prints at the end the full number of eliminated blank lines and the number of no content lines eliminated. A line full of spaces (only) is considered a blank line, and so it is eliminated. In case you don't want blank lines with spaces (they will be eliminated anyway, as they are at the end) to be eliminated, just assign spaces/tabs seen to the variable last_char.
In addition to the good answer by #LuisColorado, there a several ways you can look at your problem that may simplify things for you. Rather than using multiple conditionals to check for c == ' ' and c == '\t' and c == '\n', include ctype.h and use the isspace() macro to determine if the current character is whitespace. It is a much clearer way to go.
When looking at the return. POSIX getline uses ssize_t as the signed return allowing it to return -1 on error. While the type is a bit of an awkward type, you can do the same with long (or int64_t for a guaranteed exact width).
Where I am a bit unclear on what you are trying to accomplish, you appear to be wanting to read the line of input and ignore whitespace. (while POSIX getline() and fgets() both include the trailing '\n' in the count, it may be more advantageous to read (consume) the '\n' but not include that in the buffer filled by my_getline() -- up to you. So from your example output provided above it looks like you want both "hello" and "hel lo ", to be read and stored as "hello".
If that is the case, then you can simplify your function as:
long my_getline (char *s, size_t limit)
{
int c = 0;
long n = 0;
while ((size_t)n + 1 < limit && (c = getchar()) != EOF && c != '\n') {
if (!isspace (c))
s[n++] = c;
}
s[n] = 0;
return n ? n : c == EOF ? -1 : 0;
}
The return statement is just the combination of two ternary clauses which will return the number of characters read, including 0 if the line was all whitespace, or it will return -1 if EOF is encountered before a character is read. (a ternary simply being a shorthand if ... else ... statement in the form test ? if_true : if_false)
Also note the choice made above for handling the '\n' was to read the '\n' but not include it in the buffer filled. You can change that by simply removing the && c != '\n' from the while() test and including it as a simple if (c == '\n') break; at the very end of the while loop.
Putting together a short example, you would have:
#include <stdio.h>
#include <ctype.h>
#define MAXC 1024
long my_getline (char *s, size_t limit)
{
int c = 0;
long n = 0;
while ((size_t)n + 1 < limit && (c = getchar()) != EOF && c != '\n') {
if (!isspace (c))
s[n++] = c;
}
s[n] = 0;
return n ? n : c == EOF ? -1 : 0;
}
int main (void) {
char str[MAXC];
long nchr = 0;
fputs ("enter line: ", stdout);
if ((nchr = my_getline (str, MAXC)) != -1)
printf ("%s (%ld chars)\n", str, nchr);
else
puts ("EOF before any valid input");
}
Example Use/Output
With your two input examples, "hello" and "hel lo ", you would have:
$ ./bin/my_getline
enter line: hello
hello (5 chars)
Or with included whitespace:
$ ./bin/my_getline
enter line: hel lo
hello (5 chars)
Testing the error condition by pressing Ctrl + d (or Ctrl + z on windows):
$ ./bin/my_getline
enter line: EOF before any valid input
There are many ways to put these pieces together, this is just one possible solution. Look things over and let me know if you have further questions.

C Program doesn't end after giving the correct output

So I'm trying to do a program that reads a sequence of numbers separated by spaces and new lines. The output should be the same sequence, but erasing unnecessary zeros(The sequence of charachters 'EOF' ends the program). Per example
01492 102934 should come out as 1492 102934
9312 0 01923 should come out as 9312 0 1923
0001249 0000 should come out as 1249 0
Well I've achieved that purpose but have come across a roadblock. The program doesn't exit unless I type the EOF sequence. Maybe it's because I have a while(1) running that gives an infinite loop. But when I try to delete it the program doesn't even print at all. I'm still learning this is for a school project.
Any help would be apreciated!
Here's the code:
#include <stdio.h>
int main(){
char c;
int i=0;
while(1){
c=getchar();
if (i==0){
if(c=='0'){
while (c=='0'){
c=getchar();
}
}
printf("%c",c);
i=i+1;
}
else if (c==' '){
printf("%c",c);
c=getchar();
if(c=='0'){
while (c=='0'){
c=getchar();
}
}
printf("%c",c);
}
else if (c=='E'){
c=getchar();
if (c=='O'){
c=getchar();
if(c=='F'){
printf("\n");
return 0;
}
}
}
else{
printf("%c",c);
}
}
}
The important stuff:
int c; // IMPORTANT, cannot be char
while (1) {
c = getchar();
if (c == EOF) break; // exit loop
// ...
}
There has to be some way to tell the program to exit.
With this, the program will exit on the letter x or two consecutive newlines or entering END.
getchar will return EOF when there is nothing left to read from a file. That can be simulated from stdin ( the keyboard) with ctrl + z on Windows or ctrl + d on Linux.
#include <stdio.h>
#include <string.h>
int main ( void) {
char done[4] = "";
int c = 0;
int prior = 0;
int reading = 0;
int zero = 1;
while ( EOF != ( c = getchar ( )) && 'x' != c) {
if ( '\n' == c && '\n' == prior) {
break;
}
if ( c >= '0' && c <= '9') {
reading = 1;
if ( '0' != c) {
zero = 0;
}
if ( ! zero) {
putchar ( c);
}
}
else {
if ( reading) {
if ( zero) {
putchar ( '0');
}
if ( ' ' == c || '\n' == c) {
putchar ( c);
}
else {
putchar ( ' ');
}
}
reading = 0;
zero = 1;
}
prior = c;
done[0] = done[1];
done[1] = done[2];
done[2] = c;
done[3] = 0;
if ( 0 == strcmp ( done, "END")) {
break;
}
}
putchar ( '\n');
return 0;
}
getchar() returns an int, not a char. If it only returned a char, there would be no way for it to return a value that indicates end of file, since all char values are valid and can’t be used for another purpose.
A motivating example in decimal system may be: A function checks the temperature returns a two-digit number. Any temperature between 0 and 99 is valid. How do you report errors when the thermometer is disconnected? You have to return a number with more digits, and use a special value like UNPLUGGED = 100.
But int is a wider type: it has many more values than char, and the “extra” values can be used to indicate some special condition that means “hey, this is not a valid character, but something else I had to tell you”.
getchar() returns the EOF constant upon failure (any failure), for example if no more input is available. There’s nothing sensible you can do even if the reason for the failure other than end of input. You should end processing at the first EOF.
Thus, change the type of c to int, and every time you call getchar(), you must check that its value is not EOF, and return when you encounter it.
The nested structure of your loops means that EOF checking has to be repeated all over the place. There are other ways to structure the code to keep this check in one place, but, admittedly, the nested loops have at least the potential to exploit the branch predictor, whereas a single getchar followed by a state-machine style switch statement will make it perform potentially worse. None of this matters in a simple homework problem, but it’s something to keep in mind. In any case, performance has to be benchmarked - no other way around it.
Try this code, I think it does what you requested:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
static int getLine(char *prmpt, char *buff, size_t sz) {
int ch, extra;
// Get line with buffer overrun protection.
if (prmpt != NULL) {
printf("%s", prmpt);
fflush(stdout);
}
if (fgets(buff, sz, stdin) == NULL)
return -2;
// If it was too long, there'll be no newline. In that case, we flush
// to end of line so that excess doesn't affect the next call.
if (buff[strlen(buff) - 1] != '\n') {
extra = 0;
while (((ch = getchar()) != '\n') && (ch != EOF))
extra = 1;
return (extra == 1) ? -1 : 0;
}
// Otherwise remove newline and give string back to caller.
buff[strlen(buff) - 1] = '\0';
return 0;
}
int* convert2numbers(char* arr, int size) {
int i;
int j;
int k;
char token[100];
int* numbers;
int last_space = 0;
int index = 1;
int amount = 1;
// Count the amount of tokens.
for (i = 0; i < size; ++i) {
if (arr[i] == ' ') {
++amount;
}
}
numbers = (int *)malloc(amount * sizeof(int));
numbers[0] = amount;
for (j = 0; j <= size; ++j) {
if (arr[j] == ' ' || arr[j] == '\0') {
// Copy token from input string.
for (k = 0; k < j; ++k) {
token[k] = arr[k + last_space];
}
token[j] = '\0';
numbers[index] = atoi(token);
// Clear the token and continue.
memset(token, '\0', sizeof(token));
last_space = j;
++index;
}
}
return numbers;
}
int main(void) {
int i;
int size;
int* numbers;
int amount;
char input[100];
char help[] = "Numbers> ";
printf("Input numbers below or press enter to exit!\n");
while (1) {
getLine(help, input, sizeof(input));
// If input is empty exit.
if (input[0] == '\0') {
break;
}
size = strlen(input);
numbers = convert2numbers(input, size);
amount = numbers[0];
for (i = 1; i < amount + 1; ++i) {
printf("%d ", numbers[i]);
}
printf("\n");
}
return 0;
}
When run with these inputs this code outputs:
Input numbers below or press enter to exit!
Numbers> 01492 102934
1492 102934
Numbers> 9312 0 01923
9312 0 1923
Numbers> 0001249 0000
1249 0
Also if you press enter in console, it exits, as to escape the while(1) loop, easily.

How do I limit my user input

I've been creating a program requesting the user to input a char value, but if they enter more than one character it will move onto the next function and break the program. I've added in the second method which gets run when multiple inputs are entered.
Your problem is not one of limiting the number of characters written to cInput; the format specifier %1s does that already. Your problem is one of leaving unprocessed characters in the input buffer. You need to remove all characters from the buffer if subsequent input will not handle them. For example if you leave a alphabetic character in then buffer but later read with %d, the function will return immediately (because there is implicitly a newline also buffered), but the character will remain buffered because it is not a decimal. This will continue indefinitely if you never clear the buffer.
For a single character, you can check the character is not a newline, and then repeatedly get characters until a newline is found, as follows:
scanf("%c", &cInput ) ;
while( cInout != '\n' && getchar() != '\n' ) { } // flush buffered line
If you want to be sure the user only enters a single character, then you could modify the above thus:
scanf("%c", &cInput ) ; // Get a single character
if( cInput != '\n' && // If the input is not "empty",
getchar() != '\n' ) // but the first character entered was not
// immediately followed by a newline...
{
// Flush to the end of the entered line
while( getchar() != '\n' ) { }
// Invalidate the input to force retry
cInput = 0 ;
}
At least one character will be buffered - a newline at least. A valid answer will have two characters one in cInput and a newline. The if(...) condition above reads the second character if there is one (using short-circuit evaluation of cInput), and checks that it is the end of the input (newline). If it is not, it reads all buffered characters then invalidates cInput (in case say "No-way\n" were entered for example, so that cinput contained 'N'.
For numeric input, you simply read characters until the newline is found:
scanf("%d", &nValue);
while( getchar() != '\n' ) { } // flush buffered line
If trailing non-numeric characters should render the entire input invalid, you need to check that the following character is a newline.
int converted = scanf("%d", &nValue);
if( converted == 0 || getchar() != '\n' )
{
valid_input = false ;
while( getchar() != '\n' ) { } // flush buffered line
}
Note that there are other possible solutions. This is my preferred solution.
When applied to your functions (with other simplifications):
int intAskUser(void)
{
char cInput = 0 ;
while( cInput != 'N' && cInput != 'Y' )
{
printf("Do you want to enter a value? Y or N\n");
scanf("%c", &cInput ) ;
if( cInput != '\n' && getchar() != '\n' )
{
while( getchar() != '\n' ) { } // flush buffered line
cInput = 0 ;
}
else
{
cInput = toupper(cInput) ;
}
}
// Return answer code 0 to 1
return (cInput == 'N') ? 0 : 1 ;
}
int getValue(int nLower, int nUpper)
{
assert( nLower < nUpper ) ; // precondition check
int nValue = 0 ;
bool valid_input = false ;
while( !valid_input )
{
printf("Enter a value between %d and %d: ", nLower, nUpper ) ;
int converted = scanf("%d", &nValue);
if( converted == 0 || getchar() != '\n' )
{
valid_input = false ;
while( getchar() != '\n' ) { } // flush buffered line
}
valid_input = nValue >= nLower &&
nValue <= nUpper ;
if( !valid_input )
{
printf( "Please try again. " );
}
}
printf("Value: %d", nValue);
return nValue;
}
Note that toupper() requires ctype.h to be included, and the type bool requires stdbool.h.
If I understand your question correctly, you want the function to return if the user input is any of
y followed by newline
Y followed by newline
n followed by newline
N followed by newline
In all other cases you want to stay in the function and get new user input (e.g. nYnhhh followed by newline shall not return).
To my knowledge there is no standard function that can achieve that, so you have to write your own code.
When doing that there are two things to remember:
You must read at least 2 chars in order to check for "too long" input strings.
After unsuccessful inputs you need to empty the input buffer before reading new input. An unsuccessful input is one that doesn't have \n as last char.
Finally I recommend you use fgets() instead of scanf() as it is much easier to use. Don't use gets() though - it's dangerously vulnerable to buffer overrun.
Your code could look like:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
int AskUser(void)
{
char input[3] = {'\0'}; // Make room for a string of 2 chars + terminating null
int c;
int len;
printf("Do you want to enter a value? Y or N\n");
do
{
if (!fgets(input, 3, stdin))
{
printf("Input error");
exit(1);
}
len = strlen(input);
if (len)
{
if (input[len-1] != '\n') // Check whether last char is a newline
{
// It isn't so empty the input buffer
while ((c = getchar()) != '\n' && c != EOF) { }
}
}
if (len == 2) // Check for exactly 2 chars in input
{
if(toupper(input[0]) == 'Y' && input[1] == '\n')
{
return 1;
}
if(toupper(input[0]) == 'N' && input[1] == '\n')
{
return 0;
}
}
printf("Please enter a valid input, Y or N: \n");
} while(1);
}
int main(void) {
printf("Answer is %d\n", AskUser());
return 0;
}

Validating user input between 1-9 using getchar()

Hey guys im trying to write a small program where the user has to put in a number between 1-9, anything else is an error, but I'm having trouble validating the input because if you put 12 it only reads the 1 and it goes in the loop. It has to be done using getchar() this is what have so far:
printf(%s,"please enter a number between 1 - 9);
int c;
c = getchar();
while(c != '\n') {
int count = 1;
count ++;
if ((c >= '0' && c <= '9') || count > 1) {
printf(%s, "Congrats!);
}
else
{
print(%s, "ERROR);
}
}
I'm also having problems validating the char into an int after it goes in. If i put in 5 i get 53.
Try changing count > 1 to count == 1, and initialize it to 0 rather than 1. That way you can keep count of the number of digits you have. Also, note that because you initialize count to 1 and then immediately increment it, count > 1 will always evaluate to true, so if you gave it any char it will always say it's correct.
getchar() will return the next character typed. If you want more than the first character you will need a call getchar() again within the while loop.
//Somewhere to store the result
//initialized with an invalid result value
int digitchar = 0;
//Get the first char
int c = getchar();
while (c != '\n')
{
//Check if we already have a digit
//and that the new char is a digit
if (digitchar == 0 && c >= '1' && c <= '9')
{
digitchar = c;
}
//Get the next char
c = getchar();
}
//Check if we have stored a result
if (digitchar != 0)
{
//Success
}
Note this doesn't handle if a non-digit or newline character is entered. You would need to handle that as an error as well as if more than one digit is entered.
This is not working with 12 because getchar() takes one character per time.The following example is one way to solve it.
printf("please enter a number between 1 - 9");
int c[10], count=1;
//Declare an array because user may insert a bigger number
char number;
//This loop allow the user to enter an input
for(i=0;i<10;i++){
number = getchar();
if (number != ' '){
c[i] = atoi(number);
sum = sum + c[i];
}
else if(number == ' '){
//Terminate the loop when user stop typing
break;
}
else if( sum > 9 || sum < 0){
//Start loop again until user enter valid input
printf("You entered a number out of field try again\n");
continue;
}
}
while(c != '\n') {
count ++;
if ((c >= '0' && c <= '9') || count > 1) {
printf("%d Congrats!",c);
}
else
{
printf(" %d ERROR", c);
}
}
Remember that getchar() returns the ascii value of the char, thus when you pass the value to the function you must subtract char '0' to pass the actual decimal value into the function.
Another point is that you must clear the input buffer. If your user enters wrong input, you have to make sure that there is nothing left on the input buffer before you try to read input again.
Hope this helps.
int main(void) {
int input = 0; // 0 is the sentinel value to close program
printf("\n%s\n", "Enter value between 1-9 .\nEnter [0] to finish.");
do {
input = getchar();
if (((input>= '1') && (input <= '9') || input == '0') && getchar() == '\n') {
if ((input >= '1') && (input <= '9')) {
callYourOwnFuntionAndPassValue(input - '0');
printf("\n%s\n", "Enter value between 1-9 .\nEnter [0] to finish.");
}
}
else {
while (getchar() != '\n') {} // clear input buffer
printf("\n%s\n", "Please enter a valid number");
}
} while (input != END_PROGRAM);
return NO_ERROR; // NO_ERROR = 0
}

Resources