char ch;
int nr=0;
printf("\n: ");
ch = getchar();
while(ch != 'q' && ch != 'Q'){
ch = tolower(ch);
if(ch == 'a' || ch == 'e' || ch == 'o' || ch == 'i' || ch == 'u')
nr++;
printf("something");
ch = getchar();
}
printf("vocale: %d", nr);
its supposed to count the number of vowels until the user presses q or Q. it's such a silly program and yet i cant get past it.
Instead of using getchar
ch = getchar();
that also reads white space characters use scanf like
scanf( " %c", &ch );
Pay attention to the leading space in the format string. It allows to skip white space characters.
For example
while ( scanf( " %c", &ch ) == 1 && ch != 'q' && ch != 'Q'){
Also it will be more safer to write
ch = tolower( ( unsigned char )ch );
The problem is, that the input only gets flushed to your program whenever the user presses enter. Another reason why it seems not to work is, because you don't have a newline at the end of you output (printf("vocale: %d", nr); ), which causes the output not to be flushed to the terminal when the program ends. Fix this and your program works, but maybe not as you expect it to, because you still have to press enter. It will still only count to the first 'q' found.
int main() {
char ch;
int nr = 0;
printf(": ");
while(tolower(ch = getchar()) != 'q'){
ch = tolower(ch);
if(ch == 'a' || ch == 'e' || ch == 'o' || ch == 'i' || ch == 'u')
nr++;
}
printf("vocale: %d\n", nr);
}
The program:
: aeu q oi (here I pressed enter)
vocale: 3
Related
I need to prompt the user for a letter. If that letter is not a vowel, keep prompting until a vowel is entered.
My desired outcome is:
Enter a vowel:z
That is not a vowel. Try again:h
That is not a vowel. Try again:w
That is not a vowel. Try again:t
That is not a vowel. Try again:o
Congrats. You picked a vowel.
So far my code is:
do
{
printf("Enter a vowel: ");
scanf(" %c", &letter);
}
while (letter != 'a' && letter != 'e' && letter != 'i' && letter != 'o' && letter != 'u' && letter != 'A' && letter != 'E' && letter != 'I' && letter != 'O' && letter != 'U');
{
printf("That is not a vowel. Try again: ");
scanf(" %c", &letter);
}
printf("Congrats. You picked a vowel!!!");
Your braces, indentation and spacing are deceptive. It looks like the do has no while and that the while controls the block below it...
Try this:
/*...*/
while( 1 ) {
printf( "Enter a vowel: " );
char letter;
if( scanf( " %c", &letter ) != 1 )
exit( -1 );
if( strchr( "aeiouAEIOU", letter ) != NULL ) // found!
break;
printf( "That is not a vowel. Try again:\n\n" );
}
printf( "Congrats. You picked a vowel!!!\n" );
// NB: 'letter' has "gone out of scope".
/*...*/
strchr() searches the string supplied for a matching character, returning NULL if it is NOT found (ie: not a vowel, in this case.)
The "infinite loop" can only "break" when the user supplies a vowel.
Add a few LFs (\n) to the print statements.
Do and While should go together. So you are looking for a code that will be something like below.
Your objective should be to ensure the user is in loop till a vowel is received. Also you can further improve the code by using functions for the vowel check. Find a sample below.
do
{
printf("Enter a vowel: ");
scanf(" %c", &letter);
if (letter != 'a' && letter != 'e' && letter != 'i' && letter != 'o' && letter != 'u' && letter != 'A' && letter != 'E' && letter != 'I' && letter != 'O' && letter != 'U')
printf("Sorry, Try again \n");
} while (letter != 'a' && letter != 'e' && letter != 'i' && letter != 'o' && letter != 'u' && letter != 'A' && letter != 'E' && letter != 'I' && letter != 'O' && letter != 'U');
printf("Congrats. You picked a vowel!!!");
}
The applicable loops in C are do-while, for and while. There is no do.
Hopefully OP will see the problem once OP's code is properly formatted.
do {
printf("Enter a vowel: ");
scanf(" %c", &letter);
} while (letter != 'a' && letter != 'e' && letter != 'i' && letter != 'o'
&& letter != 'u' && letter != 'A' && letter != 'E' && letter != 'I'
&& letter != 'O' && letter != 'U');
{
printf("That is not a vowel. Try again: ");
scanf(" %c", &letter);
}
There is no error message in the loop.
A more concise way to achieve that would be using strchr(), as suggested by #tadman in the comments.
#include <stdio.h>
#include <string.h>
int main () {
char * vowels = "aeiouAEIOU";
char letter;
do {
printf("Enter a vowel: ");
scanf(" %c", &letter);
} while (strchr(vowels, letter) == NULL);
printf("Congrats. You picked a vowel!!!");
}
Look at the example:
#include<stdio.h>
int main()
{
char ch;
while(scanf("%c", &ch))
{
if(ch == 'a' || ch == 'e' || ch == 'i' ||
ch == 'o' || ch == 'u' || ch == 'A' ||
ch == 'E' || ch == 'I' || ch == 'O' ||
ch == 'U')
{
printf("It's Vowel\n");
}
else if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
{
printf("It's Consonant\n");
}
else
{
printf("Wrong Input/ It's not Alphabet\n");
}
}
return 0;
}
After compiling this example code, when I enter 'a', The output is "It's Vowel" and "Wrong Input/ It's not Alphabet". I think the cause for this output is, the compiler takes the character also takes the enter press as a character.
Is there any way to solve this problem?
I think the cause for this output is, the compiler takes the character also takes the enter press as a character.
It's not the compiler who takes characters. Getting input is a run-time operation. When the program is already running, the work of the compiler is far done, but beside that your guess is correct. It is because scanf() doesn't consume the newline character with made by the press to Enter at the first step.
This newline character then get read at the next iteration by scanf("%c", &ch)) and as the newline character is a legit character it is stored inside of ch.
Is there any way to solve this problem?
Use
while(scanf(" %c", &ch))
instead of
while(scanf("%c", &ch))
Notice the white space character (' ') before %c. This will fetch the abandoned newline character left in stdin from the last iteration.
I've encountered a problem when validating a single-char scanf input in C and I cannot find an existing solution that works...
The scenario is: a method is taking a single letter 'char' type input and then validating this input, if the criteria is not met, then pops an error message and re-enter, otherwise return this character value.
my code is:
char GetStuff(void)
{
char c;
scanf("%c", &c);
while(c != 'A' || c != 'P')
{
printf("invalid input, enter again (A for AM or P for PM): ");
scanf ("%c", &dtChar);
}
return c;
}
however, i got the infinite loop of error message no matter what input I type in. I read some other posts and guess it's the problem that %c specifier does no automatically get rid of the newline when I hit enter, and so far I have tried:
putting a white space before/after %c like:
scanf(" %c", &c);
write a separate method or include in this GetStuff method to clean the newline like:
void cleanBuffer(){
int n;
while((n = getchar()) != EOF && n != '\n' );
}
Can anyone help me with this problem please? Thank you in advance.
Please consider the following snippet:
#include <stdio.h>
#include <ctype.h>
char GetStuff(void)
{
char c;
do {
printf("Please enter A for AM or P for PM: ");
scanf ("%c", &c);
// clean input buffer (till the end of line)
while(getchar()!='\n');
} while(toupper(c) != 'A' && toupper(c) != 'P');
return c;
}
int main(void)
{
printf("Your input is'%c'\n", GetStuff());
return 0;
}
Note the points:
condition while(c != 'A' || c != 'P') will be always true (just because one character cannot be 'A' and 'P' at the same time), so use while(c != 'A' && c != 'P') instead
No need for two scanf if you use do..while loop
After entering a char with scanf it is recommended to clean all characters from buffer, e.g. with while(getchar()!='\n'); (this will clean all input including incorrect and redundant characters)
use toupper to avoid making 4 comparison (actually single c=toupper(c) inside loop can minimize your while as while(c != 'A' && c != 'P') )
UPDATE:
To add message "Invalid input" and adding some other useful improvement subjected befor... new code is as:
#include <stdio.h>
#include <ctype.h>
void CleanBuffer(){
int n;
while((n = getchar()) != EOF && n != '\n' );
}
char GetStuff(void)
{
char c;
do {
printf("Please enter A for AM or P for PM: ");
scanf (" %c", &c);
c = toupper(c); // here letter become uppercase
CleanBuffer();
} while( (c != 'A' && c != 'P')?printf("Invalid input! "):0 );
return c;
}
int main(void)
{
printf("You have entered: %c\n", GetStuff());
return 0;
}
Note: function will return 'A' or 'P' in uppercase, so if this is not needed change the code as in example before update (use two toupper and do not change c after scanf). Also you can use tolower as an option (of course with comparing to 'a' and 'p').
#include <stdio.h>
char GetStuff(void) {
char c;
scanf("%c", &c);
getchar();
while ((c != 'A') && (c != 'a') && (c != 'P') && (c != 'p')) {
printf("invalid input, enter again (A for AM or P for PM): ");
scanf ("%c", &c);
getchar();
}
return c;
}
int main(void) {
printf("Calling GetStuff()...\n");
char x = GetStuff();
printf("User entered %c\n", x);
return 0;
}
You are using while (c != 'A' || c != 'P') as your loop conditional, but this will always return true. What you meant to use is the && "and" operator, instead of the || "or" operator.
Also, call getchar() after your scanf statements, to capture the newline. This should work the way you want it to.
Inside loop you are taking input in dtChar but your loop condition checks variable c which is not updated in the loop, that is causing infinite loop
Also you would change your condition
while(c != 'A' || c != 'P')
to
while(c != 'A' && c != 'P')
If you want user to enter either 'A' or 'P'
Another possible solution. As others mentioned the condition was to be done with &&. Anyway the big problem is how to remove what's left on the console input line. Since the console works by lines, we remove everything up to the next '\n'. If the user already left something on the input line before calling GetStuff(), it would be useful to add a call to SkipRestOfTheLine() before the while loop.
In general I suggest to start with a while(1) loop, before making it nicer (such as in the cleanBuffer() you posted).
#include <stdlib.h>
#include <stdio.h>
void SkipRestOfTheLine(void)
{
while (1) {
int c = fgetc(stdin);
if (c == EOF || c == '\n')
break;
}
}
char GetStuff(void)
{
while (1) {
int c = fgetc(stdin);
if (c == EOF)
exit(EXIT_FAILURE); // Deal with this case in an appropriate way
if (c == 'A' || c == 'P')
return c;
printf("invalid input, enter again (A for AM or P for PM): ");
SkipRestOfTheLine();
}
}
int main(void)
{
char c = GetStuff();
return 0;
}
try this,
char GetStuff(void)
{
char c;
scanf("%c", &c);
while (((c != 'A') || (c != 'a')) && ((c != 'P') || (c != 'p'))==1)
{
printf("invalid input, enter again (A for AM or P for PM): ");
scanf ("%c", &dtChar);
}
return c;
}
I hope this works, some time because of not given proper bracket it is stuck in the loop.
#include <stdio.h>
int main(){
char c;
do{
printf("invalid input, enter again (A for AM or P for PM): ");
scanf ("%s", &c);
}while ((c != 'A') && (c != 'P'));
return 0;
}
This is for homework . Must use only getchar and putchar
int main(void) {
int pch; //first
int ch; //second
while(1){
pch=getchar();
ch=getchar();
if(((pch>='A' && pch<='Z')) && ((ch>='A' && ch<='Z'))){
putchar(ch);
putchar(pch);
}
if((pch>='A' && pch<='Z') && ch=='\n') putchar(pch);
if(pch=='\n' || ch=='\n') break;
}
return EXIT_SUCCESS;
}
I need to swap chars using getchar and putchar . For exemple
PARIS
APIRS
And it works , but i need to hit ENTER two times when i even number of letters 4,6,8... . How do i eliminate this behavior ? Is there some way to kill \n for getchar
I typed PAR, hit one time enter and got APR. I believe this is what you want.
Is there some way to kill \n for getchar?
You need to do something like this:
char1 = getchar();
getchar(); // To kill `\n`
char2 = getchar();
getchar(); // To kill `\n`
Source.
Also as suggested by mch, you can do:
if(pch == '\n') break; after pch=getchar();
So you should change your program to this:
#include <stdio.h>
int main(void) {
int pch; //first
int ch; //second
while (1) {
pch = getchar();
if (pch == '\n') // when you hit enter once, break the loop
break;
ch = getchar();
if (((pch >= 'A' && pch <= 'Z')) && ((ch >= 'A' && ch <= 'Z'))) {
putchar(ch);
putchar(pch);
}
if ((pch >= 'A' && pch <= 'Z') && ch == '\n')
putchar(pch);
if (pch == '\n' || ch == '\n')
break;
}
return 0;
}
Write a program that reads input up to # and reports the number of times that the sequence ei occurs.
I have little confusion with sequence such as 'ieei' where compiler does enter 3rd 'e' but never fetches 'i' with getchar(), why and if someone can improve this before myself it'd be good?
char ch;
int sq=0;
while ((ch = getchar()) != '#')
{
if (ch == 'e')
{
ch = getchar();
if (ch == 'e')
ch = getchar();
if (ch == 'i')
sq++;
}
}
printf("Sequence occurs %d %s\n", sq, sq == 1 ? "time" : "times");
In my opinion it's simplest to keep the result of the last getchar() in a variable rather than have an extra getchar() inside your loop.
char ch;
int sq=0;
char lastCh = ' ';
while((ch=getChar())!='#') {
if(lastCh=='e' && ch=='i')
sq++;
lastCh=ch;
}
This gives the correct result no matter how many e's in a row or whatever, and breaks at the first # character.
I'm tempted to implement it as:
char ch=0;
int sq=0;
do{
if( (ch=( ch=='e'? ch:getchar() )) == 'e' && (ch=getchar()) == 'i' )
++sq;
}while(ch!='#');
But it uses ?: and && for control flow, which might be confusing especially to beginners.
On second thought it's not that hard to unroll it:
char ch=0;
int sq=0;
do{
if( ch!='e' ) ch = getchar();
if( ch == 'e' ){
ch = getchar();
if( ch == 'i' ) ++sq;
}
}while(ch!='#');