C, if statements and strcmp - c

I don't understand why it does not pick up on the inputs. It always displays "Invalid Input"... Help!
while(1)
{
fgets(input, MAX, stdin);
printf("%s", input);
if(strcmp(input, "1") == 0)
{
add();
}
else if(strcmp(input, "2") == 0)
{
delete();
}
else if(strcmp(input, "3") == 0)
{
view();
}
else if(strcmp(input, "4") == 0)
{
break;
}
else
{
printf("Invalid Input!\n");
}
}

Because the value stored by fgets() contains a trailing '\n'.
Try this
int stop = 0;
while (stop == 0)
{
fgets(input, MAX, stdin);
printf("%s", input);
if (strcmp(input, "1\n") == 0)
add();
else if (strcmp(input, "2\n") == 0)
delete();
else if (strcmp(input, "3\n") == 0)
view();
else if (strcmp(input, "4\n") == 0)
stop = 1;
else
printf("Invalid Input!\n");
}
did it work?
So you need to remove it from input or adding to the comparison string.

In addition to what #iharob said, I would suggest using strncmp to check your inputs. That function lets you explicitly specify how many characters to compare. See here for a function definition.
int stop = 0;
while (stop == 0)
{
fgets(input, MAX, stdin);
printf("%s", input);
if (strncmp(input, "1", 1) == 0)
add();
else if (strncmp(input, "2", 1) == 0)
delete();
else if (strncmp(input, "3", 1) == 0)
view();
else if (strncmp(input, "4", 1) == 0)
stop = 1;
else
printf("Invalid Input!\n");
}

Related

C Case in loop problems

I have multiple errors with this project. The first and most important one would have to be one I answer a question in a case. Rather than it going back to choosing a case, it instead goes towards the difficulty. This won't let me exit the program and to get the average questions correct.
Another error is the end average questions correct. My program crashes whenever I try to just skip questions and go to the end. All it would do is divide 0/0 unless that's not possible. I'm supposed to use a switch function which is something I've seen has a problem with loops. Sadly, I can't find a way to fix it on my end, or every answer has just gone right over my head.
#include <stdio.h>
int main()
{
int option = 0;
int answer = 0;
int remainder = 0;
int ttlProblems = 0;
int correctAnswers = 0;
double averageCorrect = 0;
char difficulty;
printf("Math Practice Program Menu");
printf("\n\n1. Addition\n");
printf("2. Subtraction \n");
printf("3. Multiplication \n");
printf("4. Division \n");
printf("5. Exit\n\n");
printf("Select an option: ");
scanf_s("%d", &option);
while (option != 5)
{
switch (option)
{
case 1:
printf("Select difficulty level...\ne for easy\nm for medium\nh for hard\n");
scanf_s(" %c", &difficulty, 1);
if (difficulty == 'e')
{
printf("3 + 1 = ? Enter answer: ");
scanf_s("%d", &answer, 1);
if (answer == 4)
{
++ttlProblems;
++correctAnswers;
printf("Correct!\n");
}
else
{
++ttlProblems;
printf("Sorry, Incorrect\n");
}
}
else if (difficulty == 'm')
{
printf("34 + 19 = ? Enter answer: ");
scanf_s("%d", &answer, 1);
if (answer == 53)
{
++ttlProblems;
++correctAnswers;
printf("Correct!\n");
}
else
{
++ttlProblems;
printf("Sorry, Incorrect\n");
}
}
else if (difficulty == 'h')
{
printf("134 + 119 = ? Enter answer: ");
scanf_s("%d", &answer, 1);
if (answer == 253)
{
++ttlProblems;
++correctAnswers;
printf("Correct!\n");
}
else
{
++ttlProblems;
printf("Sorry, Incorrect\n");
}
}
else
{
printf("Invalid difficulty set\n");
}
break;
case 2:
printf("Select difficulty level...\ne for easy\nm for medium\nh for hard\n");
scanf_s(" %c", &difficulty, 1);
if (difficulty == 'e')
{
printf("3 - 1 = ? Enter answer: ");
scanf_s("%d", &answer, 1);
if (answer == 2)
{
++ttlProblems;
++correctAnswers;
printf("Correct!\n");
}
else
{
++ttlProblems;
printf("Sorry, Incorrect\n");
}
}
else if (difficulty == 'm')
{
printf("34 - 19 = ? Enter answer: ");
scanf_s("%d", &answer, 1);
if (answer == 15)
{
++ttlProblems;
++correctAnswers;
printf("Correct!\n");
}
else
{
++ttlProblems;
printf("Sorry, Incorrect\n");
}
}
else if (difficulty == 'h')
{
printf("134 - 119 = ? Enter answer: ");
scanf_s("%d", &answer, 1);
if (answer == 15)
{
++ttlProblems;
++correctAnswers;
printf("Correct!\n");
}
else
{
++ttlProblems;
printf("Sorry, Incorrect\n");
}
}
else
{
printf("Invalid difficulty s\n");
}
break;
case 3:
printf("Select difficulty level...\ne for easy\nm for medium\nh for hard\n");
scanf_s(" %c", &difficulty, 1);
if (difficulty == 'e')
{
printf("3 * 1 = ? Enter answer: ");
scanf_s("%d", &answer, 1);
if (answer == 3)
{
++ttlProblems;
++correctAnswers;
printf("Correct!\n");
}
else
{
++ttlProblems;
printf("Sorry, Incorrect\n");
}
}
else if (difficulty == 'm')
{
printf("34 * 19 = ? Enter answer: ");
scanf_s("%d", &answer, 1);
if (answer == 646)
{
++ttlProblems;
++correctAnswers;
printf("Correct!\n");
}
else
{
++ttlProblems;
printf("Sorry, Incorrect\n");
}
}
else if (difficulty == 'h')
{
printf("134 * 119 = ? Enter answer: ");
scanf_s("%d", &answer, 1);
if (answer == 15946)
{
++ttlProblems;
++correctAnswers;
printf("Correct!\n");
}
else
{
++ttlProblems;
printf("Sorry, Incorrect\n");
}
}
else
{
printf("Invalid difficulty set\n");
}
break;
case 4:
printf("Select difficulty level...\ne for easy\nm for medium\nh for hard\n");
scanf_s(" %c", &difficulty, 1);
if (difficulty == 'e')
{
printf("9 / 2 = ? Enter answer: ");
scanf_s("%d", &answer, 1);
printf("Enter any remainder: ");
scanf_s("%d", &remainder, 1);
if (answer == 4 && remainder == 1)
{
++ttlProblems;
++correctAnswers;
printf("Correct!\n");
}
else
{
++ttlProblems;
printf("Sorry, Incorrect\n");
}
}
else if (difficulty == 'm')
{
printf("34 / 19 = ? Enter answer: ");
scanf_s("%d", &answer, 1);
printf("Enter any remainder: ");
scanf_s("%d", &remainder, 1);
if (answer == 1 && remainder == 15)
{
++ttlProblems;
++correctAnswers;
printf("Correct!\n");
}
else
{
++ttlProblems;
printf("Sorry, Incorrect\n");
}
}
else if (difficulty == 'h')
{
printf("134 / 19 = ? Enter answer: ");
scanf_s("%d", &answer, 1);
printf("Enter any remainder: ");
scanf_s("%d", &remainder, 1);
if (answer == 7 && remainder == 1)
{
++ttlProblems;
++correctAnswers;
printf("Correct!\n");
}
else
{
++ttlProblems;
printf("Sorry, Incorrect\n");
}
}
else
{
printf("Invalid difficulty set\n");
break;
}
break;
case 5:
break;
default:
printf("Not a valid option.\n");
}
}
averageCorrect = ttlProblems / correctAnswers;
printf("You attempted %d problems and got %d correct\nFor a percentage of %.2f correct.", ttlProblems, correctAnswers, averageCorrect);
}
Currently, your code asks the user to enter the option type before the while loop, so it will only ask once and use that value for the option every loop iteration. Moving your option input scanf_s("%d", &option); into the beginning of the while loop should solve your first problem.
In regards to dividing by zero, this will cause the program to crash because it is not possble. You might want to check whether correctAnswers is zero or not before performing the division.

yes or no to exit a switch statement

Is it possible to create yes or no function to be called to exit a switch statement. if (y)es is hit it would exit. If (n)o is hit it would loop back to the switch's options. if so how would this be done. This is what I have so far.
I hope this helps to clarify what I am trying to do
int yes_no(void) {
scanf("%d", &option);
while (option == 'y' || option == 'Y' || option == 'n' || option == 'N') {
if (option == 'y' || option == 'Y') {
return 1;
} else
if (option == 'n' || option == 'N') {
return 0;
} else {
printf("Only (Y)es or (N)o are acceptable");
}
}
}
int main(void) {
int select;
do {
printf("0 exit");
printf("1 hello");
scanf("%d", &select);
switch (select) {
case 0:
printf("Exit the program? (Y)es or (N)o :");
yes_no(); // if (n)o is hit it will loop back to the menu
break;
case 1:
printf("hello how r u doing");
break;
default:
printf("not accepted number");
}
} while (select != 0);
}
Consider the following yes_no function.
int yes_no() {
char option;
while (1) {
printf("(y/n): ");
if (scanf(" %c", &option) != 1) {
printf("Error occurred while reading option.\n");
continue;
}
if (option == 'y' || option == 'Y') {
return 1;
} else if (option == 'n' || option == 'N') {
return 0;
} else {
printf("Only (y)es or (n)o are acceptable.\n");
}
}
}
You have a return value of 1 if given a yes input, and 0 in case of no. With this in mind, in the case 0 code block of the switch statement, the return value of this function can be captured, which can then be used to either break the loop or do nothing. For example:
int main(void) {
int select;
int continue_loop = 1;
printf("Press 0 to exit\n");
printf("Press 1 for hello\n\n");
while (continue_loop) {
printf("(0/1): ");
if (scanf(" %d", &select) != 1) {
printf("Error occurred while reading number.\n");
continue;
}
switch (select) {
case 0:
printf("Exit the program? (y)es or (n)o;\n");
int make_sure = yes_no(); // yes_no() returns 1 if 'yes', and 0 if 'no'
// If 'yes', break while loop by setting continue_loop to 0.
// Do nothing in case of 'no'
if (make_sure == 1) {
continue_loop = 0;
}
break;
case 1:
printf("Hello, how are you doing?\n");
break;
default:
printf("Number not accepted.\n");
}
}
return 0;
}
This should do the job, if I get your question correctly:
int yes_or_no()
{
do
{
char option = 0;
scanf(" %c", &option);
if (option == 'y' || option == 'Y')
return 1;
if (option == 'n' || option == 'N')
return 0;
printf("Only (Y)es or (N)o are acceptable");
}
while( 1 );
}
with switch you can perform your code better:
int yes_no(void) {
scanf("%d", &option);
while (1){
switch(option){
case 'y':
case 'Y':
return 1;
case 'n':
case 'N':
return 0;
default:
printf("invalid input.try again");
scanf("%d", &option);
}
}
}

calculating color band of resistor values and output them

I'm trying to develop a C program that calculates the resistor values by inputting the colour bands marked on the resistor.
Ignoring the resistor tolerance
here is my code
output must be similar to Calculating the resistor value with its color bands as input
my codes below doesnt give me what i wanted.I want it to be able to loop back for y and no.output must be separated {3}{3}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <ctype.h>
int bandChoice;
char colorOne[10];
char colorTwo[10];
char colorThree[10];
float codeOne;
float codeTwo;
float codeThree;
float x;
void colorCodes();
void multiplier();
void color_code(char codeOne);
int main(void)
{ printf("Enter the colors of the resistor three bands, beginning with the band nearest the end. Type the colors in lowercase letters only, NO CAPS\n");
puts(" ");
printf("Band 1 = >");
scanf("%s",colorOne);
puts(" ");
printf("Band 2 = >");
scanf("%s",colorTwo);
puts(" ");
printf("Band 3 = >");
scanf("%s",colorThree);
puts(" ");
printf("%f %f %f\n",colorOne,colorTwo,colorThree);
x=(codeOne*10)+codeTwo;
printf("Resistance value %d");
}
void color_code(char codeOne )
{
if(strcmp(colorOne, "black") == 0)
{
codeOne=0;
}
else
if(strcmp(colorOne, "brown") == 0)
{
codeOne=1;
}
else
if(strcmp(colorOne, "red") == 0)
{
codeOne=2;
}
else
if (strcmp(colorOne, "orange") == 0)
{
codeOne=3;
}
else
if (strcmp(colorOne, "yellow") == 0)
{
codeOne=4;
}
else
if (strcmp(colorOne, "green") == 0)
{enter code here
codeOne=5;
} else
if (strcmp(colorOne, "blue") == 0)
{
codeOne=6;
} else
if (strcmp(colorOne, "violet") == 0)
{
codeOne=7;
} else
if (strcmp(colorOne, "gray") == 0)
{
codeOne=8;
} else
if (strcmp(colorOne, "white") == 0)
{
codeOne=9;
} else
{
printf("Invalid colors\n");
}
}
void multiplier()
{
if(strcmp(colorThree, "black") == 0)
{
codeThree=1;
} else
if(strcmp(colorThree, "brown") == 0)
{
codeThree=10;
} else
if(strcmp(colorThree, "red") == 0)
{
codeThree=pow(10.0,2);
} else
if (strcmp(colorThree, "orange") == 0)
{
codeThree=pow(10.0,3);
} else
if (strcmp(colorThree, "yellow") == 0)
{
codeThree=pow(10.0,4);
} else
if (strcmp(colorThree, "green") == 0)
{
codeThree=pow(10.0,5);
} else
if (strcmp(colorThree, "blue") == 0)
{
codeThree=pow(10.0,6);
} else
if (strcmp(colorThree, "violet") == 0)
{
codeThree=pow(10.0,7);
} else
if (strcmp(colorThree, "gray") == 0)
{
codeThree=pow(10.0,8);
} else
if (strcmp(colorThree, "white") == 0)
{
codeThree=pow(10.0,9);
} else
{
printf("Invalid colors\n");
}
}
http://imgur.com/rya9egk
really appreciate if someone can help
Your color_code function is not properly designed. You should take in as an input the color string and return the code string.
.
char color_code(char *colorOne )
{
char codeOne;
if(strcmp(colorOne, "black") == 0)
{
codeOne=0;
}
// and so on for other colors
// at the end
return codeOne;
}
In the main, you need to call this color_code function like this, after the scanf's
.
codeOne = color_code(colorOne);
You also need to repeat this for the other three functions.
The variables colorOne colorTwo colorthree codeOne codeTwo codeThree can be made local to main, instead of global.

Returning to start of loop C

I want to return to the start of the loop and make the user enter another input.
This is what I have but I keep getting the error message repeating over and over again.
How would I return so the user can enter a argument
printf("Enter a option\n");
scanf("%d", &option);
while (option != 1 || option != 2 || option != 3 || option != 4)
{
if (option == 1)
{
option1(...);
break;
}
else if (option == 2)
{
option2(...);
break;
}
else if (option == 3)
{
option3(...);
break;
}
else if (option == 4)
{
option4(...);
break;
}
else
{
printf("\nPlease enter a correct option\n");
continue;
}
}
Just rearrange the logic, for example like:
do {
printf("Enter a option\n");
scanf("%d",&option);
if(option == 1){
option1(...);
break;
}
else if(option == 2){
option2(...);
break;
}
else if(option == 3){
option3(...);
break;
}
else if(option == 4){
option4(...);
break;
}
else{
printf("\nPlease enter a correct option\n");
continue;
}
}
while(true);
Now your code does the scanf only once and then iterates over the same result, instead you must read the value each time you begin the loop.
int option;
while(1)
{
printf("Enter a option\n");
scanf("%d",&option);
if(option == 1){
printf("option1\n");
break;
}
else if(option == 2){
printf("option2\n");
break;
}
else if(option == 3){
printf("option3\n");
break;
}
else if(option == 4){
printf("option4\n");
break;
}
else{
printf("\nPlease enter a correct option\n");
continue;
}
}
use a do..while with printf/scanf inside.
do {
printf("Enter a option\n");
scanf("%d",&option);
your if/else statements here...
} while(true);
you should Change your loop to do while.
do
{
printf("Enter a option\n");
scanf("%d",&option);
if(option == 1){
option1(...);
}
else if(option == 2){
option2(...);
}
else if(option == 3){
option3(...);
}
else if(option == 4){
option4(...);
}
else{
printf("\nPlease enter a correct option\n");
continue;
}
}while(option != 1 || option != 2 || option != 3 || option != 4);

Line in text file is evaluated multiple times?

I need to convert infix to postfix and evaluate postfix expression. When reading from a file, I should be able to evaluate multiple expressions at once. But when I run it and it encounters an expression that is not well-formed in the sense that there are more closed parentheses than open ones, it evaluates that expression 2 or 3 times.
Code:
#include <stdio.h>
#include <conio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#define MAX 1000
typedef struct stack
{
int data[MAX];
int top;
} stack;
int priority(char);
void init(stack*);
int empty(stack*);
int full(stack*);
char pop(stack*);
void push(stack*, char);
char top(stack*);
void add(char*, char, int);
void keyboard();
void read_file();
int change(char);
void pushYO(double);
double popYO();
stack s;
char x;
int i, token, topYO = -1;
double result[MAX];
char filepath[MAX];
int main()
{
char choice;
init(&s);
system("CLS");
printf("[1] Keyboard \n[2] Read from text file \n[3] Exit \n");
scanf("%c", &choice);
if(choice != '1' && choice != '2' && choice != '3')
{
main();
}
else if(choice == '1')
{
keyboard();
}
else if(choice == '2')
{
read_file();
}
else if(choice == '3')
{
printf("\nThank you for using Kei Shirabe's \ninfix to postfix converter and evaluator! :)\n");
exit(0);
}
}
void keyboard() //the keyboard input version. this works fine
{
//code here
}
void read_file()
{
int z, count, form, paren;
double one, two, three = 1;
char infx[MAX];
char pofx[MAX];
char choice;
FILE *text = fopen("text.txt", "a");
printf("Enter path of file:");
scanf("%s",&filepath);
FILE *textYO = fopen(filepath, "r");
if((textYO) == NULL)
{
printf("\nError! Unable to open %s\n\n", filepath);
}
else
{
while((fgets(infx, MAX, textYO))!= NULL)
{
form = -1, paren = 0, count = 0, z = 0;
infx[
strlen(infx)-1] = '\0';
for (i=0; i<strlen(infx); i++)
{
if((token = infx[i]) != '\n')
{
if(isalnum(token))
{
form++;
}
else
{
if(token == '(')
{
paren++;
}
else if(token == ')')
{
paren--;
}
else
{
form--;
}
}
if (paren < 0)
{
printf("%s", infx);
fprintf(text, "%s", infx);
printf("\n\nError! Not well formed :( \n-----------------\n");
fprintf(text, "\n\nError! Not well formed :( \n-----------------\n");
}
else
if(isalnum(token))
{
add(pofx, token, count);
count++;
}
else
if(token == '(')
{
push(&s, '(');
}
else
{
if(token == ')')
while((x = pop(&s)) != '(')
{
add(pofx, x, count);
count++;
}
else
if(token == '^')
{
push(&s, token);
}
else
{
while(priority(token) <= priority(top(&s)) && !empty(&s))
{
x = pop(&s);
add(pofx, x, count);
count++;
}
push(&s, token);
}
}
}
else
{
while(!empty(&s))
{
x = pop(&s);
add(pofx, x, count);
count++;
}
}
}
if(form != 0 || paren != 0)
{
printf("%s", infx);
fprintf(text, "%s", infx);
printf("\n\nError! Not well formed :( \n-----------------\n");
fprintf(text, "\n\nError! Not well formed :( \n-----------------\n");
}
else
{
form = -1, paren = 0;
printf("%s", infx);
fprintf(text, "%s", infx);
printf("\n\nPostfix: %s \n\n", pofx);
fprintf(text, "\n\nPostfix: %s\n\n", pofx);
while((token = pofx[z++]) != '\0')
{
three = 1;
if(!isdigit(token) && !isalpha(token))
{
two = popYO();
one = popYO();
switch(token)
{
case '+':
pushYO(one+two); break;
case '-':
pushYO(one-two); break;
case '*':
pushYO(one*two); break;
case '/':
pushYO(one/two); break;
case '^':
if (two > 0)
{
for(i=0;i<two;i++)
{
three = three * one;
}
pushYO(three);
three = 1; break;
}
else
{
for(i=0;i<(two-(2*two));i++)
{
three = three * one;
}
pushYO((1/three));
three = 1; break;
}
}
}
else if(isalpha(token))
{
if(isupper(token))
{
pushYO(token - '#');
}
if(islower(token))
{
pushYO(token - change(token));
}
}
else
{
pushYO(token - '0');
}
}
printf("Result: %lf\n-----------------\n", result[topYO]);
fprintf(text, "Result: %lf\n-----------------\n", result[topYO]);
}
}
}
fclose(text);
fclose(textYO);
printf("\nRun again? \n[1] Yes \n[any other key] No\n");
scanf("%c", &choice);
scanf("%c", &choice);
if(choice == '1')
{
main();
}
else
{
printf("\nThank you for using Kei Shirabe's \ninfix to postfix converter and evaluator! :)\n");
exit(0);
}
}
//other functions down here, not important
Sample text file (and yes there is an extra space at the end):
(1+2))
(1+2*3)
For this text file, the expression (1+2)) is evaluated three times, each result being "Not well formed". The last expression works as expected.
Any help please?

Resources