I have written a program in C to count characters input from stdin. I wanted to use a loop to allow more than one entry. (Note: I am new to programming.)
main()
{
long nc;
int c;
int kc=1;
for (kc=1;kc<=5;kc=kc+1)
{
nc=0;
c= getchar();
while(c != '0')
{
++nc;
c=getchar();
}
printf("%1d\n",nc);
}
return 0;
}
So basically as you would guess, the loop accepts 5 entries.
PROBLEM: When I enter Sky0 the first result is all right, 3. But from then on, one is added to the count. That is entering dame0 results in a count of 5, sit0 results in a count of 4 etc.
While trying to debug the problem using prinf at various stages, I realized that after the first result the code finds the end of the input, 0, but enters the for loop NEVERTHELESS and waits for the next entry with nc as 1. That leads to the error in corresponding outputs.
Please tell where I'm going wrong? And why is it entering the loop even after sensing 0?
Greatly appreciate your help and time :)
The problem is that when you press enter, that becomes a character too (value 0x1a), and it is returned by the getchar call outside the while loop.
You could do something like:
while (getchar() != '\n') nc++;
In that way you do not even need to use a 0 to mark the end of the string.
Related
Output
Code:
#include<stdio.h>
main()
{
int c;
printf("Enter any charachter!: ");
while((c = getchar()) != EOF) {
putchar(c);
printf("%d\n", (c = getchar()) != EOF);
}
}
I've tried to test out EOF in C and I'm having a difficult time with it. I've wanted to get the value of EOF and found out that it is -1.
I wrote a simple program using getchar() and putchar().
I have added the screenshot of the program and output. Output doesn't make any sense to me.
As you can see I'm trying to get a character and display it using getchar() and putchar(). And I'm trying to print out the value of the condition used in the while loop. To check the EOF I'm deliberately entering -1 as input. putchar() prints out -1 and then the final printf statement confuses me. I enter -1 for getchar() but 1 displayed meaning c is not equal to EOF. But I thought -1 is EOF.
And I don't understand why 11 is also displayed. I'm using codeblocks IDE.
Please help me. Thanks in advance.
EOF isn’t a character, and it isn’t read from the stream. It’s just the return value indicating that there is no more input on that stream. You can signal an EOF by typing CtrlD on *nix or CtrlZ on Windows.
getchar takes input one character(byte) at a time. so when you input '-1' it is treated as a character array input and first getchar takes input only '-' and second one takes input '1'. Thus you are not getting your desired output. Also putchar is designed to print one character at a time. So it might not work properly too. You can change your code following way to make it work.
int c;
while(scanf("%d", &c)!=EOF) { //to ensure there is some input value as scanf will return EOF when input stream finishes.
printf("%d\n", c);
if(c == EOF) {
printf("c is equal to EOF\n");
break;
}
}
OK so after reading these previous questions:
Alternate method for clearing input buffer in c
How to clear input buffer in C?
I came up with a piece of code to empty the input buffer and count how many values were in the buffer, then return this number. A comparison is then made to check if the number exceeded the allowed number.
#include <stdio.h>
#include <stdlib.h>
int Empty();
int main()
{
double x;
int y=0;
while(y==0)
{
y=1;
if(scanf("%lf",&x)!=1 || Empty()>1) //checks if the value is acceppted
// and then attempts to empty
// the input buffer. I always expect
//at least 1 returned due to the
// EOF or '\n'
{
fprintf(stdout,"Invalid character(s) entered, please re-enter.\n");
y=0;
}
}
return(x);
}
int Empty()
{
int clearr,n=0;
do
{
n++;
}while((clearr=fgetc(stdin))!= EOF && clearr !='\n'); // If EOF or '\n' is reached
// it ends, returning the
//number of characters
return(n);
}
If i then run the program and enter 2 or 2.2 etc, the number is accepted and returned.
If i enter 2a, or 2 a or 2 2 etc it always catches the space/letter/etc and forces a SINGLE loop to allow you to try and reenter a value
If, however if enter the offending item, i.e the a, first then an infinite loop occurs.
This does not make sense to me as from what i understand, when the fgetc(stdin) is called it MUST pull either a character or an EOF which would signify only one item has been entered, ending the loop.
In a test if( A || B ), if A is true, B is not evaluated.
So if scanf("%lf",&x)!=1 is true, Empty() is not called and your loop continues forever.
One of the problems here is that you try to do several things at once, the advice would be:
keep things simple
no side effects
So 1) scan the input, 2) if it's ok move on, 3) if it's not flush and repeat.
If you enter a , scanf("%lf",&x) will give 0 and hence it never calls Empty.
#include<stdio.h>
#include<conio.h>
int main() {
long nc;
nc = 0;
while (getchar()!= EOF){
++nc;
printf("%ld\n", nc);
}
return 0;
}
My question is: When I input a number or a character, it increments twice >.<
for example: I ran the program, I typed 1, then its going to output
1
2
can someone please tell me why >< cause isn't it suppose to just increment 1? And the value of nc that the program is gonna show is 1? Then its going to become 2 when i enter another number or character?
After entering any number you are pressing Enter key.
and as '\n' != EOF so it is running two times.
int main() {
long nc;
nc = 0;
while (getchar()!= '\n'){ // check for enter key here.
++nc;
printf("%ld\n", nc);
}
return 0;
}
When you input a number and press Enter key, an additional \n character passed to the standard input buffer. getchar reads that number leaving behind \n in the buffer. On next iteration of loop getchar reads \n before pressing any character by you and hence inside while for second time.Hence value is printed twice as \n is not there.
Use below while condition and this shall fix the issue.
while(getchar() != '\n');
This will eat up any number of \n.
I have a glitch in this code and am not sure how to fix it.
I would like to read an inputed string of random characters one character at a time.
Once an invalid character is read, I would like the program to stop reading the string and prompt the user to input a new string.
The program will also only read and store up to 5 characters regardless of string length unless the end of string is met before this 5 character limit.
code:
int check; //1 = invalid char in string, 2 = otherwise
char c;
char seq[5];
do{ printf("Enter a string of only "+" and "-" \n");
for(i=0; c!=EOF || i<5 ; i++){
scanf("%c",&seq[i]);
if((seq[i] != '\x2b') || (oseq[i] != '\x2d')){
printf("invalid sequence, try again\n");
check=1;
break;
}
check=2;
}
}while(check==1);
Please help, I know it's a simple solution but it's just not coming to me and I've searched/tried everything.
I should add that this code keep reading and will print out every time it reaches an invalid char without letting the user input a new one until it reaches the end of the string.
Consider what your for current for loop is going to do:
for(i=0; c!=EOF || i<5 ; i++){
For i starting with 0, run while c is not EOF or i is less than 5.
So if c is not EOF, i is 0, 1, 2, 3, 4, 5, 6, 7, ... 1000, because our code ignores i as long as "c != EOF".
Accessing seq[1000] is not what you want.
Moreso, as far as c is concerned, your initial iteration of the for loop checks for c != EOF but you never initialized c to a value. That is undefined behavior and c could be anything, so your loop may run or may never run of c happens to start out with the same value as EOF is defined as.
I recommend you just simplify to:
for(i=0; i<5 ; i++){
Then keep your validity check inside the loop, if c is EOF or some other invalid value, use break to exit the for loop and keep your for(...) conditions simple. This change will fix both of the issues with your for loop.
Besides that, you stated the intention was to store up to 5 characters. In C, if you intend to treat the character array as a string, you must allow room for the trailing null terminating character, so always use N + 1 for your array size. You should use seq[6] if you intend to print it later, and make sure to set the last character of the string (after you read the last one) to 0 (or '\0').
Per your infinite loop problem you are being caught out by the age old beginner's luck of using scanf() which is a poor input function. I've been coding in C for 20 years and to be honest, I forgot how to use scanf effectively 19 years ago because it just is ill suited for most input needs (I love its brother printf, but thats a different story). scanf() will scan exactly what you ask for, but if it doesn't handle an input, it will leave it unscanned. If you consider when you input a character and hit return, you are actually entering 2 characters (counting the \n on UNIX or 3 on Windows/DOS counting \r\n). In your case, you are buffering up additional characters each iteration.
You can clear the input buffer with something like this after your scanf() call.
while ((ch = getchar()) != '\n' && ch != EOF);
But I avoid scanf() and use fgets() or getchar() directly. scanf() is to be avoided. All C programmers start by learning scanf() in school, then they eventually learn it is to be avoided for anything but formatted files.
I believe you are not initializing the variable called 'c'...
perhaps declare it with
char c = null;
or
char c = 0;
and use it in your loop
scanf("%c",&c);
seq[i] = c;
otherwise your check for c != EOF will be spurious / ambiguous / undefined
Also, the first time it enters the loop and checks for
for(i=0; c!=EOF || i<5 ; i++)
...you have not set the value for c - so anything could happen unexpectedly, and you are using OR instead of AND. It should be:
for(i=0; c!=EOF && i<5 ; i++)
It's my first time posting here, so hopefully this goes as intended.
I'm doing one of the early exercises from K&R. The objective is to use getchar() to get a bunch of characters from the user, and then print them using putchar(), but skipping any extra spaces. My solution to the exercise works great, but I don't understand why.
Here's the program:
#include <stdio.h>
int main()
{
int c, spc;
c = 0;
spc = 0;
while(c != EOF)
{
c = getchar();
if(c == ' ')
{
if(spc != 1)
{
putchar(c);
spc = 1;
}
}
if(c != ' ')
{
spc = 0;
putchar(c);
}
}
return 0;
}
There is only one loop, and execution stops during the first iteration when it hits getchar() as expected. Once carriage return is pressed, the program proceeds to print out whatever the user typed into the buffer, sans extra spaces - exactly what it's supposed to do.
But what I don't understand is why execution doesn't stop with each subsequent iteration of the loop when it comes across getchar(). Does the /n character have something to do with it? I did notice that it also prints the newline, and after every thing is printed it again stops at getchar(). So, why is it skipping over getchar() at the start of each iteration while printing everything in the buffer?
I've been toying with C for a long while, but only recently have made an effort to learn it the 'right' way. Since I have some experience you don't have to dumb your answers down too much (so, like you're explaining it to a 10 year old instead of a 5 year old).
When you type stuff and you hit enter, everything is stored in an internal buffer. So every time the loop executes, it hits getchar who *does * go to that buffer and pulls a single character.
But what I don't understand is why execution doesn't stop with each
subsequent iteration of the loop
The program stops only in the event where getchar doesn't find anything in that buffer.
Now \n has nothing special in this case. It's just the convention that the CLI doesn't actually "send" what you type to the program until you hit return (i.e. you can hit backspace and so on).
while (c != EOF) ends after hitting EOF. Try pressing Ctrl + D after some input.