I am trying to write a while loop which only runs as user input is 'F' or 'C'. However, my while loop seems doesn't work. Could you show me what is wrong with my scanf and while loop condition
#include <stdio.h>
#include <stdlib.h>
int main()
{
char response;
while (response == 'F' || response == 'C')
{
printf(" Please enter F or C\n");
scanf(" %c", &response);
}
return 0;
}
response is uninitialized. Your code hasn't even gotten to the scanf() yet. Consider changing it to a do-while loop.
You have to initialize response, try this
#include <stdio.h>
#include <stdlib.h>
int main()
{
char response;
response = 'F';
while (response == 'F' || response == 'C')
{
printf(" Please enter F or C\n");
scanf(" %c", &response);
}
return 0;
}
and you can of course do it this way
#include <stdio.h>
#include <stdlib.h>
int main()
{
char response;
/* since you don't check for `scanf()`'s return value,
* this prevents undefined behavior
*/
response = 'F';
do {
printf(" Please enter F or C\n");
scanf(" %c", &response);
} while (response == 'F' || response == 'C');
return 0;
}
Your loop runs as long as response is 'F' or 'C'. What you need is
while (response != 'F' && response != 'C')
Also, response is not initialized. Start with
char response = '\0';
There are two common ways to do a terminate-on-input loop in C:
do {
...get input...
do_stuff();
} while (...input does not indicate exit...);
or
while (1) {
...get input...
if (...input indicates exit...) break;
do_stuff();
}
I think the latter might work better for your case:
while (1) {
printf(" Please enter F or C\n");
scanf(" %c", &response);
if ('F' == response) {
do_f();
} else if ('C' == response) {
do_c();
} else {
break;
}
}
Related
I'm new to C and this is my TicTacToe for first C project. For that, I setup a simple process for user where to choose X or O. But it doesn't seem to work for reason. Here it continues to the if statements and goes into infinite loop cause it didn't wait for user input.
I've gone through similar forums about this exact question but I was unable to get an answer that fixed my problem. Also, feedbacks about the code are much appreciated because I do want to improve my code.
#include <stdio.h>
#include <stdlib.h>
void main()
{
char checks_player;
int is_input_valid = 0;
while(is_input_valid == 0)
{
printf("What do you want to choose? (X/O) ");
scanf(" %c",checks_player);
if(checks_player == 'x')
{
checks_player = 'X';
is_input_valid = 1;
}
else if(checks_player == 'o')
{
checks_player = 'O';
is_input_valid=1;
}
else if((checks_player == 'O')|| (checks_player == 'X'))
{
is_input_valid = 1;
}
else
{
printf("Invalid Input!!\nTry Again.\n\n");
}
}
}
You need to pass a pointer to scanf. Instead of this:
scanf(" %c",checks_player);
Use this:
scanf(" %c", &checks_player);
I want so that when the user enters e it will run my function called enter and scan in values but all I get is VECRQ?:, why is this? Did I call upon the function wrong?
I tried having the while loop to 1 also instead of menuoption != 'q' didn't work. I was thinking that with the menuoption is not equal to 'q' it will keep the loop running until the user actually enters 'q' to shut the program off.
#include <stdio.h>
int enter(int measurments[], int nrOfmeasurments)
{
while(nrOfmeasurments<10)
{
printf("Enter measurment #%d (or q to quit): ",nrOfmeasurments+1);
int oneMeasurment;
int readInteger = scanf("%d",&oneMeasurment);
if(readInteger)
{
measurments[nrOfmeasurments] = oneMeasurment;
nrOfmeasurments ++;
//return nrOfmeasurments;
}
else
{
char tmp;
scanf(" %c",&tmp);
break;
}
}
if(nrOfmeasurments==10)
{
printf("Array is full\n");
}
return nrOfmeasurments;
}
int main(void)
{
int measurments[10];
int nrOfmeasurments;
char menuoption;
printf("Measurment tool 2.0\n");
while (menuoption != 'q')
{
printf("VECRQ?:\n");
scanf(" %c",&menuoption);
if (menuoption == 'e')
{
//int MeasurmentData[10];
//int nrOfmeasurments;
//enter(measurments, nrOfmeasurments);
nrOfmeasurments = enter(measurments, nrOfmeasurments);
}
else if(menuoption == 'v')
{
}
else if(menuoption == 'c')
{
}
else if(menuoption == 'q')
{
printf("Exiting Measurment tool 2.0\n");
break;
}
}
}
Don't forget to init your variables with default values. Your problem is that nrOfmeasurments is not initialized and have some trash value. Also, set a default value to menuoption for some non q char to be sure, that your loop will be executed at least one time
I have just started off with C programming and while I was trying to write a programme to accept only y or n characters I came across that
#include <stdio.h>
#include <stdlib.h>
int main()
{
char ch;
printf("Do you want to continue\n");
for (;;)
{
ch=getchar();
if (ch=='Y' || ch=='y')
{
printf("Sure!\n");
break;
}
else if (ch=='N'||ch=='n')
{
printf("Alright! All the best!\n");
break;
}
else
{
printf("You need to say either Yes/No\n");
fflush(stdin);
}
}
return(0);
}
When I run this code, and type in any other character other than Y/y or N/n, I receive the last printf statement (You need to say either Yes/No) as output twice.
I understand that this is happening because it considers enter, i.e, '\n' as another character.
Using fflush doesn't help as it's an infinite loop.
How else can I modify it so that the last statement is displayed only once?
You can use a loop to read any characters left using getchar():
ch=getchar();
int t;
while ( (t=getchar())!='\n' && t!=EOF );
The type of ch should int as getchar() returns an int. You should also check if ch is EOF.
fflush(stdin) is undefined behaviour per C standard. Though, it's defined for certain platforms/compilers such as Linux and MSVC, you should avoid it in any portable code.
Another option - use scanf ignoring white spaces.
Instead of ch=getchar();, just need scanf( " %c", &ch );
With this you can also get rid of fflush(stdin);
Like is said in my comment you should use int ch instead of char ch because the return type of getchar which is int.
To clean stdin you could do something like the following:
#include <stdio.h>
#include <stdlib.h>
int main(void){
int ch,cleanSTDIN;
printf("Do you want to continue\n");
for (;;)
{
ch = getchar();
while((cleanSTDIN = getchar()) != EOF && cleanSTDIN != '\n');
if (ch=='Y' || ch=='y')
{
printf("Sure!\n");
break;
}
else if (ch=='N'||ch=='n')
{
printf("Alright! All the best!\n");
break;
}
else
{
printf("You need to say either Yes/No\n");
}
}
return(0);
}
Any way a do while will probably do the job for you:
#include <stdio.h>
#include <stdlib.h>
int main(void){
char ch;
int check;
do {
printf("Do you want to continue: ");
if ((scanf("%c",&ch)) == 1){
while((check=getchar()) != EOF && check != '\n');
if ((ch == 'y') || (ch == 'Y')){
printf("Alright! All the best!\n");
break;
} else if((ch == 'n') || (ch == 'N')){
printf("You choosed %c\n",ch);
break;
}else{
printf("You need to say either Yes/No\n");
}
}else{
printf("Error");
exit(1);
}
}while (1);
return 0;
}
Output1:
Do you want to continue: g
You need to say either Yes/No
Do you want to continue: y
Alright! All the best!
Output2:
Do you want to continue: n
You choosed n
Or we can simply use another break; statement after the last printf().
I am trying to debug a program which were I am getting the values 'S' or 'P' from standard input. My function calc_resistance() needs to distinguish between these two cases as well as a case were neither 'S' nor 'P' has been entered. The program always evaluates to the third case (neither 'S' nor 'P'`), why is this so?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
float calc_resistance(char conn) {
float retval = 0.0;
if (conn == 'S') {
retval = 1;
}
else if (conn == 'P') {
retval = 2;
}
else {
retval = -1;
}
return retval;
}
int main() {
char connection_type[25];
float resistance = 0.0;
while(1) {
printf("Enter 'S' or 'P': ");
scanf("%s", connection_type);
if(strlen(connection_type) != 1 ||
(strncmp(connection_type,"S",25) && strncmp(connection_type,"P",25))) {
printf("Answer not understood. Enter 'S' or 'P'.\n");
continue;
}
break;
}
resistance = calc_resistance(connection_type);
printf("Connection type: %f", resistance);
}
The mistake you're doing is to pass an array to the calc_resistance() function when it is defined to accept only a single char.
Seeing the input pattern, connection_type doesn't need to be an array, with the help of %c format specifier, you can easily make connection_type a single char variable to work on the input.
You can read more about this on the man page of scanf(). Also, after each iteration, don't forget to sweep out the remaining newline.
Moral of the story :: Enable compiler warnings and pay heed to them.
You want to detect the first two cases right? if yes then try this one instead of passing the whole address in your function calc_resistance(connection_type) only pass one character then try, You can modify the code as below.
#include
#include
#include
float calc_resistance(char conn)
{
float retval = 0.0;
if (conn == 'S')
{
retval = 1;
}
else if (conn == 'P')
{
retval = 2;
}
else
{
retval = -1;
}
return retval;
}
int main()
{
char connection_type[25];
float resistance = 0.0;
while(1)
{
printf("Enter 'S' or 'P': ");
scanf("%s", connection_type);
if (strlen(connection_type) != 1 || (strncmp(connection_type,"S",25) && strncmp(connection_type,"P",25)))
{
printf("Answer not understood. Enter 'S' or 'P'.\n");
continue;
}
break;
}
resistance = calc_resistance(connection_type[0]);
printf("Connection type: %f", resistance);
}
I have a problem with my input for my program:
#include <stdio.h>
#include <stdlib.h>
int confirm()
{
char c;
printf("Confirm (y/n): ");
scanf("%c", &c);
while (scanf("%c", &c))
{
if (c == 'Y' || c == 'y' || c == 'N' || c == 'n')
{
printf("\nThank you. \n");
break;
}
else
{
printf("\nInput not recognised, ry again. \n");
printf("Confirm (y/n): ");
}
}
}
int main(int argc, char* argv[])
{
confirm();
return 0;
}
When it executes, it asks the first question and inputting the answer is fine. However after entering the character (either y or n) the program prints the second question and stops. The whole program is not running. I don't know what I'm doing wrong.
Loose the first scanf at line 9 and (for me) it then seem to work correctly: if ynYN is entered then the confirm function exits, otherwise it continues looping