I know there are many questions on the same topic of scanf until EOF is reached, but here's a particular case I haven't seen. Suppose I want to make a C program where the user enters a single character, and the program prints back the character and the number of times the user has entered a character until they press CTRL+D (EOF)
This is what I have:
#include <stdio.h>
int main(){
char thing;
int i=0;
while(scanf("%c", &thing) != EOF){
printf("time:%d, char:%c\n",i,thing);
i++;
}
return 0;
}
However, the output is not as expected. It's the following:
f
time:0, char:f
time:1, char:
p
time:2, char:p
time:3, char:
m
time:4, char:m
time:5, char:
I'm not too sure why i is being incremented again, and why printf gets executed again. Perhaps I'm missing something.
Try
#include <stdio.h>
int main(){
char thing;
int i=0;
while(scanf("%c", &thing) != EOF){
if (thing!='\n') {
printf("time:%d, char:%c\n",i,thing);
i++;
}
}
return 0;
}
#user2965071
char ch;
scanf("%c",&ch);
With such a snippet one reads any ASCII character from the stream including new line, return, tab, or escape. Thus, inside the loop I would test the symbol read with one of the ctype-functions.
Something like this:
#include <stdio.h>
#include <ctype.h>
int main(){
char thing;
int i=0;
while(1 == scanf("%c", &thing)){
if (isalnum(thing)) {
printf("time:%d, char:%c\n",i,thing);
i++;
}
}
return 0;
}
As for me, I think it's not a good idea to check scanf for returning EOF. I would rather check for the number of good read arguments.
Related
My code should delete all vowels from the string that i give. But it does not delete if the vowel is the last character of the string.
#include <stdio.h>
#include <string.h>
int main()
{
int i=0;
char str[100];
printf("Enter a string :\n");
gets(str);
int len=strlen(str);
while(str[i]!='\0')
{
printf("%c",str[i]);
if(str[i]=='A'||str[i]=='a'||str[i]=='E'||str[i]=='e'||str[i]=='I'||str[i]=='i'||str[i]=='O'||str[i]=='o'||str[i]=='U'||str[i]=='u')
printf("\b");
i++;
}
return 0;
}
Like if i provide the string Hello it prints Hllo where it should print Hll ...But if i change the while condition to (i
I guess printing \b doesn’t do what you think it does. It does not delete the last printed character, it just prints an additional ‘backspace’ character, which on some output devices (such as console) moves backwards by one character. (Then, the next character overwrites the one you wanted ‘deleted’.)
Don’t do that. Instead, move the ‘if’ statement so that you don’t print those vowels in the first place!
You can try this
#include <stdio.h>
#include <string.h>
int main()
{
int i=0;
char str[100];
printf("Enter a string :\n");
fgets(str,100, stdin);
int len=strlen(str);
while(str[i]!='\0')
{
if(str[i]=='A'||str[i]=='a'||str[i]=='E'||str[i]=='e'||str[i]=='I'||str[i]=='i'||str[i]=='O'||str[i]=='o'||str[i]=='U'||str[i]=='u'){
continue;
}else{
printf("%c",str[i]);
}
i++;
}
return 0;
}
I have to develop a program that reads characters from the keyboard and write them on screen. However if the character entered is a lowercase letter than it must be converted to an uppercase letter. The reading finishes´after a line (when we press the ENTER key).
My attempt:
int main(void)
{
char c;
printf("Please enter characters. Press ENTER when you are finished\n");
do
{
scanf(" %c", &c);
if (c<='z' && c>='a')
c= c-32;
printf("%c\n", c);
} while(c!='\n');
return EXIT_SUCCESS;
}
However, the program never ends and I don't how do I do that. I'm also not sure if, even though if I insert like 5 characters and the program prints them, if this is the correct form to program it. A character is a character, a single character, it seems to me that it doesn't make much sense that it reads and prints five characters.
Can someone explain what's wrong?
In while(c!='\n');, '\n' is a special whitespace character which is ignored by scanf and thus you will never read it. To terminate you need to specify a terminating character. For example "stop if user enters character x"
then the terminating condition should be while(c!='x');
char can only get one character. So if you want to end your loop you can use like while (c != '0');
For uppercase letter you can use toupper() function from <ctype.h> Library
explanation of what is wrong with the following code:
int main(void)
{
char c;
printf("Please enter characters. Press ENTER when you are finished\n");
do
{
scanf(" %c", &c);
if (c<='z' && c>='a')
c= c-32;
printf("%c\n", c);
} while(c!='\n');
return EXIT_SUCCESS;
}
missing the statement: #include <stdio.h>
call to scanf() has space before %c which causes white space to be consumed/discarded and space, tab, newline are all white space
calculation of uppercase is not desirable. Much better to simply call toupper() which also requires the statement: #include <ctype.h>
when calling scanf() should always check the returned value (not the parameter value) to assure the operation was successful.
the defined value EXIT_SUCCESS requires the statement: #include <stdlib.h>
There are a lot less problems using getchar() rather than scanf()
it is usually a good idea to have the program pause before exiting so you can look at the results on the terminal
getchar() returns an int, not a char
toupper() expects a int parameter and returns an int
EOF is a int, usually with the value -1
Suggest the following code:
#include <stdio.h> // getchar(), printf(), perror(), EOF
#include <stdlib.h> // exit(), EXIT_SUCCESS, EXIT_FAILURE
#include <ctype.h> // toupper(), isalpha(), isdigit(), ispunct()
int main(void)
{
int ch;
printf("Please enter characters. Press ENTER when you are finished\n");
do
{
ch = getchar();
if( !isalpha( ch )
&& !isdigit( ch )
&& !ispunct( ch )
&& !('\n' == ch ) )
{ // then not a printable char
continue;
}
if( EOF == ch )
{
break;
}
ch = toupper(ch);
printf("%c\n", ch);
} while( '\n' != ch );
return EXIT_SUCCESS;
} // end function: main
Note: it would be a good idea to have the program pause, before exiting, so user can look at the output.
I've tried to use character data type to compare in variable reply if equal to y it will continue calling the function recursion(), however, it did only 1 recursion() call and the program terminated. This only work if I use the int data type, as the variable to compare. Please anyone can let me know why this happen?
#include <stdio.h>
void recursion()
{
char reply;
printf("Continue?:");
reply=getchar();
if(reply=='y')
{
printf("Continued\n");
recursion();
}
}
int main()
{
recursion();
return(0);
}
output:
Laptop1:User1$ ./recur
Continue?:y
Continued
Continue?:Laptop1:User1$
getchar() will read newline character if it is, and it will prevent it from continueing.
Try this:
#include <stdio.h>
int getchar2()
{
int c;
do
{
c = getchar();
} while (c == '\n'); /* ignore newline characters */
return c;
}
void recursion()
{
int reply;
printf("Continue?:");
reply=getchar2();
if(reply=='y')
{
printf("Continued\n");
recursion();
}
}
int main()
{
recursion();
return(0);
}
The problem is that when end-users enter 'y' in the terminal, they press Enter. This inserts another character into the stream - '\n'. That is the character that the next call to getchar() would return, ending the chain of calls due to
if(reply=='y')
condition evaluating to "false".
You can fix the problem in several ways - for example, by using scanf:
if (scanf(" %c", &reply) == 1 && reply == 'y')
// ^
// Note the space above
Adding a space character in front of %c ensures that scanf skips whitespace characters before reading the character into reply variable.
I am making a text based game, and i am having a big problem with input. Here is a small example of my problem code.
#include <stdio.h>
#include <stdlib.h>
char c;
int main(int argc, char *argv[]){
system("clear");
while(1){
printf("\nInput a character.\n");
c = getchar();
printf("\nYour input: %c\n", c);
sleep(1);
system("clear");
}
return 0;
}
So, if you compile/run this, and type in 'abc', it will just take each one, and send it through the loop. What I need it to do is only take the very first character that someone types in, no matter how many they do type in.
And, PS: I have tried it this way, and it does the same thing:
#include <stdio.h>
#include <stdlib.h>
char c[2];
int main(int argc, char *argv[]){
system("clear");
while(1){
printf("\nInput a character.\n");
scanf("%1s", c);
printf("\nYour input: %c\n", c[0]);
sleep(1);
system("clear");
}
return 0;
}
EDIT: It also adds a space to what ever you type in, I assume it is a \0, but im not sure. Thanks!
When you use scanf, enter a string and hit the ENTER key, a string and a character are placed in the input buffer, they are namely: the entered string and the newline character. The string or character by character gets consumed by the scanf but the newline remains in the input buffer, unless you consume that too.
getchar(), on the other hand will not wait for ENTER key, it would read character by character, then your logic.
I think you can add 1 more line to read all the characters that come after the first one until there is a newline character (i.e. the user presses Enter):
while (getchar() != '\n');
Adding to your example, it would be like this:
#include <stdio.h>
#include <stdlib.h>
char c;
int main(int argc, char *argv[]){
system("clear");
while(1){
printf("\nInput a character.\n");
c = getchar();
printf("\nYour input: %c\n", c);
sleep(1);
system("clear");
while (getchar() != '\n');
}
return 0;
}
Use getch() which does not wait for a newline.
What i think you look for is something like this code, to save very first character, you can also check if c == '\n' to continue your operation, but i dont know what you want after saving very first character:
int i,c;
char save;
for ( i = 0;(c=getchar())!= EOF ; i++)
{
if ( i == 0)
save = c;
}
You can use fgets(), and extract its first character, like...
char ch[2], c;
fgets(ch, 2, stdin);
c = ch[0];
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char p,q;
printf("Hello enter char: ");
p=getchar();
printf("the char is: %c\n",p);
printf("Hello enter char: ");
q=getchar();
printf("the char is: %c\n",q);
return 0;
}
(WHY IS MY OUTPUT for the second printf and scanf not waiting for me to input a char before exiting the program?.....what i mean is u know where it says q=getchar();??? shouldnt it wait for to input a char before exiting the program? but for some reason the program just exits when it goes to the next line...
when pressing enter,a character '\n' is inputing.So your getchar() was used before you enter the second character.I think you want the code below:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char p,q;
printf("Hello enter char: ");
p=getchar();
printf("the char is: %c\n",p);
int c;
while((c = getchar()) != '\n' && c != EOF && c != ' ') ;
printf("Hello enter char: ");
q=getchar();
printf("the char is: %c\n",q);
return 0;
}
You can also use a getch() instead of getchar() to avoid pressing enter key.
#include <stdio.h>
#include <conio.h>
int main(void)
{
char p,q;
printf("Hello enter char: ");
p=getch();
printf("the char is: %c\n",p);
printf("Hello enter char: ");
q=getch();
printf("the char is: %c\n",q);
return 0;
}
When encountering invalid user inputs, use getchar() to read char, and other similar instances where there are undesired characters stuck at input stream(like in your case it was a newline) I define a constant named FLUSH
#define FLUSH while(getchar() != '\n')
to solve the problem. What this statement does is that it reads a character and then throws it away. Now if you try to place it after one of your getchars i.e.
p=getchar();
printf("the char is: %c\n",p);
FLUSH;
it will read the newline then stops because the condition within the while statement no longer holds.
Note: Using getchar() for prompts leaves a '\n' in the input stream you will find this troublesome once you make another prompt and have not eradicated that '\n'.