C - While loop not exiting how expected with string input - c

I want to exit my do-while loop when the user enters "exit" from the command line. I'm trying to do it without using strcmp() but it's just not performing how I think it should. When testing it if the user enters e for the first character, or x for the second character, or i for the third, or t for the fourth character then the program exits. It's probably something simple that I'm missing. So can anyone explain why this isn't working how I'm expecting? Thanks.
#include <stdio.h>
#define FLUSH while(getchar() != '\n');
int main(){
char input[20] = {0};
printf("This is a string math program. Enter a string 9 characters or less"
" followed by an operater and finally another string 9 characters or less."
" There should be no spaces entered. To exit the program type exit.\n");
do{
printf("Input: ");
scanf("%s",input);
FLUSH
} while((input[0] != 'e') && (input[1] != 'x') && (input[2] != 'i') && (input[3] != 't'));
}

Let's talk about De Morgan's Law. This:
(input[0] != 'e') && (input[1] != 'x') && (input[2] != 'i') && (input[3] != 't')
is required to be true for your loop to continue. It is equivalent to this:
!(input[0] == 'e' || input[1] == 'x' || input[2] == 'i' || input[3] == 't')
So yes, your loop will stop when any character matches. Just use strcmp, but if you can't for some bizarre reason, just change the above logic.

Related

While loop in C prints the same line more than once

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

How can we ignore the enter button press as a character in c programming at the time of taking input from user?

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.

C - how to exclude other inputs in a y/n loop

So I am trying to get a simple y/n input to work. I have it working and it will break a while(1) loop when n or N is entered, however, any other alphabetical character will set the loop to go again. I only want it to loop when Y is entered.
I have tried:
if (try_another != 'n' || try_another != 'N' || try_another != 'y' || try_another != 'Y'), after the !isalpha line, and this did not work.
I have tried scanf (" %c", try_another); and then comparing the assigned characters.
this is my current code set up:
printf("Do you wish to try another problem [y/n]: ");
do{
try_another = getchar();
/*keeps scanning for input until its a letter*/
}while(!isalpha(try_another));
/*when input is n or N it will end the program*/
if (try_another == 'n' || try_another == 'N'){
break;
}
Why don't you do this?
do {
try_another = getchar();
} while(try_another != 'n' && try_another != 'N' && try_another != 'y' && try_another != 'Y');
You want to loop while the character isn't this and isn't that. You were close, but accidentally wrote "or" instead of "and".

How to use loops in terms of input (in C language)?

I've been trying to get this code to work but the loop does not seem to work? I am very new to C and I sort of get confused with the syntax of this language. However my loop is not functioning like how I want it to be. I want the if and else statement to work but no matter what input (right or wrong) it always outputs "thank you".
#include <stdio.h>
#include <stdlib.h>
int confirm()
{
char c;
printf("Confirm (y/n): ");
scanf("%c", &c);
while (scanf("%c", &c))
{
if (c = 'Y' && 'y' && 'N' && 'n')
{
printf("\nthank you");
break;
}
else
{
printf("\nInput not recognised, try again. \n");
printf("\nConfirm (y/n): ");
scanf("%c", &c);
}
}
}
int main(int argc, char* agrv[])
{
confirm();
return 0;
}
it won't ask to enter another output when the output is incorrect. It just keeps ending from the if statement, thus the loop is not running?
Please help.
There's nothing wrong with your loop - it's the if statement that's wrong.
This code compiles, but it does not do what you want it to do:
if (c = 'Y' && 'y' && 'N' && 'n')
= is an assignment; you need == to do a comparison
&& means "AND"; you need ||, which means an "OR"
You combine logical expressions, not constants with && or ||
The condition should be
if (c == 'Y' || c == 'y' || c == 'N' || c == 'n')
Also note that when you read single characters with %c, your program "sees" all characters, including whitespace. This is a problem, because the '\n' left over in the buffer will be passed to your program before Y or N. To fix this, add a space before %c to your format string:
scanf(" %c", &c)
// ^
// |
// Here
Your code also ignores the first character that it reads. I think this is not intentional, so remove the call of scanf before the loop. You should also remove the second scanf from the loop, leaving the only call to scanf in the loop header.
int confirm()
{
char c;
printf("Confirm (y/n): ");
//scanf("%c", &c);// <---------- needless
while (scanf("%c", &c)) //<----while loop will do `scanf("%c",&c)`, so previous line should be remove.
{
if (c == 'Y' || c == 'y' || c == 'N' || c == 'n')// <- &&(AND); ||(OR). Also, be careful that don't be lazy, [c == 'Y' || 'y' || 'N' || 'n'] can't to communicate with computer
{
printf("\nthank you");
break;
}
else
{
printf("\nInput not recognised, try again. \n");
printf("\nConfirm (y/n): ");
scanf("%c", &c);
}
}
}

Why does the message print twice?

I am creating a simple Tic Tac Toe for C, and here is a particular function which I am having a problem with. This is supposed to let the user select 'X' or 'O', and for the most art it works. However, if I enter a wrong symbol, it prints the statement:
"Invalid symbol, please re-enter: " twice.
Why and how can I fix this?
char assign(void)
{
char user;
printf("Would you like to be X or O (Enter your choice): ");
user=getchar();
while(user != 'X' && user != 'x' && user != 'O' && user != 'o')
{
printf("Invalid symbol, please re-enter: ");
user=getchar();
}
if(user == 'O' || user == 'o') return('O');
else if(user == 'X' || user == 'x') return('X');
}
The problem cause is related to the newline charachter
use scanf() in this way instead of using getchar()
scanf(" %c", &user);
It's because when you use getchar it returns the next character, but leaves the newline in the input buffer. So the next getchar returns that newline.
You should also be careful because getchar actually returns an int and not a char.
You can solve this either by another getchar, or use scanf like this:
scanf("%c ", &user);
Note the space after the c in the above format, it tells scanf to read and disregard trailing whitespace.
You could also read a line with e.g. fgets and then use a simple sscanf on that line, then no extra space is needed.
You could fix it like this for example:
char assign(void)
{
char user;
char throwaway_newline;
printf("Would you like to be X or O (Enter your choice): ");
user=getchar();
throwaway_newline = getchar();
while(user != 'X' && user != 'x' && user != 'O' && user != 'o')
{
printf("Invalid symbol, please re-enter: ");
user=getchar();
throwaway_newline = getchar();
}
if(user == 'O' || user == 'o') return('O');
else if(user == 'X' || user == 'x') return('X');
}
You have a newline in your input buffer.
When you press a character which is not [xX] and not [oO] and follow it with a newline. getchar actually gets to see 2 characters(the newline and the invalid character)
You may want to use fgets instead of relying on character input and ignoring newlines with 2 getchar() calls everytime.

Resources