Code crashes after scanf in while loop - c

The problem is in this function. It's supposed to validate input for two variables as integers. What did I do wrong? O__O Thanks :)
I used an if else statement to check for change in the variable valid so that it will exit the loop once the right input is given. Even if I input the right values, the code still crashes.
void input(int *n1, int *n2, char *opt)
{
int valid = 0;
int v2 = 0;
char choice;
int a, b;
while (v2 == 0)
{
printf("Enter first number: \n");
if(scanf("%d", &a) == 1)
{
while(v2 == 0)
{
printf("Enter second number: \n");
if(scanf("%d", &b) == 1)
{
v2 =1;
getchar();
}
else
{
getchar();
printf("Invalid input!\n");
}
}
getchar();
}
else
{
getchar();
printf("Invalid input!\n");
}
}
while( valid == 0)
{
printf("Addition -> 1\nSubtraction -> 2\nMultiplication -> 3\nDivision -> 4\nReset -> R\nExit -> E\n");
scanf("%c", &choice);
if (choice == 'r' || choice == 'e')
{
choice = toupper(choice);
}
if ((choice == '1') || (choice == '2') || (choice == '3') || (choice == '4') || (choice == 'R') || (choice == 'E'))
{
valid = 1;
}
else
{
printf("Invalid input!\n\n");
}
}
*opt = choice;
*n1 = a;
*n2 = b;
}
Here's the whole code for reference. The answers earlier were able to fix the crash. Now, either the loop doesn't exit or it doesn't work right.
#include <stdio.h>
#include <ctype.h>
int add(int n1, int n2);
int subtract(int n1, int n2);
int multiply(int n1, int n2);
int divide(int n1, int n2);
void input(int *n1, int *n2, char *opt);
int main(void)
{
int n1, n2, ret;
char opt;
start:
input(&n1, &n2, &opt);
switch(opt)
{
case '1':
ret = add(n1, n2);
printf("The sum is %d\n", ret);
break;
case '2':
ret = subtract(n1, n2);
printf("The difference is %d\n", ret);
break;
case '3':
ret = multiply(n1, n2);
printf("The product is %d\n", ret);
break;
case '4':
ret = divide(n1, n2);
printf("The quotient is %d\n", ret);
break;
case 'R':
goto start;
break;
case 'E':
printf("Goodbye!\n");
return 0;
break;
}
goto start;
}
void input(int *n1, int *n2, char *opt)
{
int valid = 0;
int v2 = 0;
char choice;
int a, b;
while (v2 == 0)
{
printf("Enter first number: \n");
if(scanf("%d", &a) == 1)
{
while(v2 == 0)
{
printf("Enter second number: \n");
if(scanf("%d", &b) == 1)
{
v2 =1;
getchar();
}
else
{
getchar();
printf("Invalid input!\n");
}
}
getchar();
}
else
{
getchar();
printf("Invalid input!\n");
}
}
while( valid == 0)
{
printf("Addition -> 1\nSubtraction -> 2\nMultiplication -> 3\nDivision -> 4\nReset -> R\nExit -> E\n");
scanf("%c", &choice);
if (choice == 'r' || choice == 'e')
{
choice = toupper(choice);
}
if ((choice == '1') || (choice == '2') || (choice == '3') || (choice == '4') || (choice == 'R') || (choice == 'E'))
{
valid = 1;
}
else
{
printf("Invalid input!\n\n");
}
}
*opt = choice;
*n1 = a;
*n2 = b;
}
int add(n1, n2)
{
int result;
result = (n1+n2);
return result;
}
int subtract(n1, n2)
{
int result;
result = (n1-n2);
return result;
}
int divide(n1, n2)
{
int result;
result = (n1/n2);
return result;
}
multiply(n1, n2)
{
int result;
result = (n1*n2);
return result;
}

Change
if(scanf("%d", a) != 0)
to
if(scanf("%d", &a) == 1)
// ^^^^ This is the right check
// ^^^ Missing &
scanf return EOF if it fails to assign to the first receiving argument. In this case, it will return 1 if data was successfully read into &a.
Similarly, change
if(scanf("%d", b) != 0)
to
if(scanf("%d", &b) == 1)
// ^^^ ^^^^

Instead of
if(scanf("%d", a) != 0)
You should use
if(scanf("%d", &a))
Scanf could return 0,1 or EOF out of which only 1 indicates no error in input!
However if your a was a pointer to some integer address location you could have used the former code.Change it for inputting b as well

Related

How can I fix my problem about terminating the program instead of repeat it from the start using while loop? C Language

I have new problem about while-loop!
When I input the l_res as y it means that the condition of while loop is still TRUE, instead repeat it from the start, it terminated the program. → enter image description here
int main()
{
//VARIABLES
char f_res[4];
char l_res = 'y';
int a,b,c,x;
while(l_res == 'y')
{
printf("Enter 3 digit capacitor Code: ");
scanf("%d %d %d",&a,&b,&c);
x = (a*10)+b;
printf("What is the unit of the value?(Pico-picofarad, Nano-Nanofarad): ");
scanf("%s", f_res);
if(strcmp(f_res, "Pico") == 0)
{
if(c == 0)
{
x = x;
}
else
{
while(c <= 5 && c > 0)
{
c--;
x = x*10;
}
}
printf("\nCapacitor value is: %d pF\n\n",x);
}
else if(strcmp(f_res, "Nano") == 0)
{
float x = ((a*10)+b)*0.001;
if(c == 0)
{
x = x;
}
else
{
while(c <= 5 && c > 0)
{
c--;
x = x*10;
}
}
printf("\nCapacitor value is: %.3f pF\n\n",x);
}
else
{
printf("\nINVALID Input!\n\n");
}
printf("Do you want to enter other capacitor Code?( y-Yes, n-No): ");
scanf(" %c", l_res);
}
return 0;
}
How can I fix this?

How to pass string from a file to a function? Converting infix to postfix

// Function push
void push(char x){
stack[++top] = x;
}
//Function pop
char pop(){
if(top == -1)
return -1;
else
return stack[top--];
}
//Arithmetic operator precedence
int priority(char x){
if(x == '(')
return 0;
if(x == '+' || x == '-')
return 1;
if(x == '*' || x == '/')
return 2;
else
return -1;
}
//Function to convert infix to postfix
char postfix(){
char *e, x = '\0';
char exps[20];
e = exps;
printf("\nEnter an expression: \n");
scanf("%s",exps);
while(*e != '\0') //While loop to arrange stack
{
if(isalnum(*e)) //isalnum convert character to ASCII code
printf("%c",*e);
else if(*e == '(')
push(*e);
else if(*e == ')')
{
while((x = pop()) != '(')
printf("%c", x);
}
else
{
while(priority(stack[top]) >= priority(*e))
printf("%c",pop());
push(*e);
}
e++;
}
while(top != -1)
{
printf("%c",pop());
}
exit(0);
return 0;
}
//Function to read file called default input
char read_file(){
char file_location[100];
int user_option=1;
FILE *fp;
character =ch;
while (user_option == 1) {
printf("Enter the location of the file:\n\n");
getchar();
gets(file_location);
fp = fopen(file_location,"r"); //read file
if( fp == NULL )
{
perror("Error while opening the file, \n\n");
exit(EXIT_FAILURE);
}
printf("The contents of the %s file are :\n\n" , file_location);
while( ( *ch = fgetc(fp) !=EOF))
printf("%s" ,ch);
fclose(fp);
postfix();
break;
}
return 0;
}
int manual_input() {
int choice=0;
while(choice == 0)
{
printf("\n\t\t\t\tMENU");
printf("\n\t------------------------------");
printf("\n\n\t 1. Postfix");
printf("\n\t 2. Prefix");
printf("\n\t 3. Both");
printf("\n\t 4. Exit");
printf("\n\tWould you like to convert it to: ");
scanf( "%d", &choice );
switch(choice)
{
case 1:
printf("\nYOU SELECTED OPTION 1 %c",1);
break;
case 2:
printf("\nYOU SELECTED OPTION 2 %c",2);
break;
case 3:
printf("\nYOU SELECTED OPTION 3 %c",3);
break;
default:
printf("\nYOU SELECTED OPTION 4 %c",4);
exit(0);
}
postfix();
}
return 0;
}
int main(){
printf("\nHi ,how would you like to input expression? \n");
printf("1.Get from file\n");
printf("2.Input own expression\n");
scanf("%d",&option);
if (option == 1) {
read_file();
} else {
manual_input();
}
}
Alright so I know my codes a little messy, had some problems indenting certain parts of code. Hopefully you can still understand. So my question is how do I get the characters from the file default.txt and pass it to my postfix function?
In my read_file function I manage to print the characters (ch) using a while loop. My goal here is to store the string so my postfix function can perform some calculation on it since I am trying to convert infix to postfix.
If you're wondering, this program gets user to choose whether to enter an expression through a file or manual input. The expression (which is an infix) is then converted to postfix.
Thanks
like this
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX_EXP_LEN 256
//Stringification
#define S_(n) #n
#define S(n) S_(n)
int top = -1;
char stack[MAX_EXP_LEN];
void push(char x){
stack[++top] = x;
}
char pop(void){
if(top == -1)
return -1;
else
return stack[top--];
}
int priority(char x){
if(x == '(')
return 0;
if(x == '+' || x == '-')
return 1;
if(x == '*' || x == '/')
return 2;
else
return -1;
}
void postfix(const char *exps){//Use the input expression as an argument
const char *e = exps;
char x = '\0';
while(*e != '\0'){
if(isalnum(*e))
printf("%c",*e);
else if(*e == '(')
push(*e);
else if(*e == ')'){
while((x = pop()) != '(')
printf("%c", x);
} else {
while(priority(stack[top]) >= priority(*e))
printf("%c", pop());
push(*e);
}
e++;
}
while(top != -1){
printf("%c", pop());
}
puts("");
}
void read_file(char exps[MAX_EXP_LEN + 1]){
char file_location[FILENAME_MAX+1] = "";
FILE *fp;
printf("Enter the location of the file:\n\n");
scanf("%" S(FILENAME_MAX) "[^\n]%*c", file_location);
fp = fopen(file_location, "r");
if( fp == NULL ){
perror("Error while opening the file.\n\n");
exit(EXIT_FAILURE);
}
fscanf(fp, "%" S(MAX_EXP_LEN) "s", exps);
fclose(fp);
}
void manual_input(char exps[MAX_EXP_LEN + 1]){
printf("Input expression\n");
scanf("%" S(MAX_EXP_LEN) "s", exps);
}
int main(void){
char exps[MAX_EXP_LEN + 1] = "";
int option;
printf("\nHi ,how would you like to input expression? \n");
printf("1.Get from file\n");
printf("2.Input own expression\n");
scanf("%d", &option);
scanf("%*[^\n]");scanf("%*c");//clear stdin
if (option == 1)
read_file(exps);//exps pass to function
else
manual_input(exps);
postfix(exps);
}

System error after installing from setup file

I created a c program in visual studio 2015 and I made a setup file
the setup file works fine in my computer . So i decided to sent the setup file to my friend , though the setup file was installed successfully when we run the program it shows system error "the program can't star because VCRUNTIME140D.dll is missing from your computer.Try re-installing the program"
here is the program I wrote ( which works perfectly )
#define _CRT_SECURE_NO_DEPRECATE
#include<stdio.h>
#include<string.h>
void beg();
void beg2();
void beg3();
void beg4();
void beg5();
void beg6();
void beg7();
void beg8();
void beg9();
void beg10();
void store_a();
void the_end();
void wrong();
void right();
void help();
int i,m;
char b[101],a[101];
void main()
{
int diff;
i = 0;
printf("\n WELCOME THO THE GAME \n"); //welcome
printf(" ARE YOU READY !!\n");
do
{
printf("\n 1.play\t 2.help\t 3.exit\n"); //menu
printf(" Enter your option : ");
scanf(" %d", &diff);
switch (diff)
{
case 1:
{
beg();
break;
}
case 2:
{
help();
break;
}
case 3:
{
break;
}
}
} while (diff != 3);
}
void beg()
{
int b;
m = 2;
printf("\n what is the capital of india?\n");
printf(" options\n");
printf(" 1.New Delhi\n 2.Mumbai\n 3.Kochi\n 4.Chennai\n");
scanf("%d", &b);
if (b == 1)
{
right();
beg2();
}
else
{
wrong();
beg2();
}
}
void beg2()
{
int b;
m = 3;
printf("\n 12 + 11 = ?\n");
printf(" options\n");
printf(" 1.12\n 2.45\n 3.23\n 4.17\n");
scanf("%d", &b);
if (b != 3)
{
b = 2;
wrong();
beg3();
}
else
{
while (b == 3)
{
if (b == 3)
{
right();
beg3();
break;
}
}
}
}
void beg3()
{
int b;
m = 4;
printf("\n who is the prime minister of india ?\n");
printf(" options\n");
printf(" 1.Pranab Mukherjee\n 2.narendra modi\n 3.manmohan singh\n 4.steven thomas\n");
scanf("%d", &b);
if (b != 2)
{
b = 1;
wrong();
beg4();
}
else
{
while (b == 2)
{
if (b == 2)
{
right();
beg4();
break;
}
}
}
}
void beg4()
{
int b;
m = 5;
printf("\n 5 x 7 = ?\n");
printf(" options\n");
printf(" 1.32\n 2.54\n 3.25\n 4.35\n");
scanf("%d", &b);
if (b != 4)
{
b = 1;
wrong();
beg5();
}
else
{
while (b == 4)
{
if (b == 4)
{
right();
beg5();
break;
}
}
}
}
void beg5()
{
int b;
m = 6;
printf("\n which country is paris the capital of?\n");
printf(" options\n");
printf(" 1.India\n 2.France\n 3.England\n 4.China\n");
scanf("%d", &b);
if (b != 2)
{
b = 1;
wrong();
beg6();
}
else
{
while (b == 2)
{
if (b == 2)
{
right();
beg6();
break;
}
}
}
}
void beg6()
{
int b;
m = 7;
printf("\n what is the capital of america?\n");
printf(" options\n");
printf(" 1.Los Angeles\n 2.New York \n 3.Washington, D.C.\n 4.Las Vegas\n");
scanf("%d", &b);
if (b != 3)
{
b = 1;
wrong();
beg7();
}
else
{
while (b == 3)
{
if (b == 3)
{
right();
beg7();
break;
}
}
}
}
void beg7()
{
int b;
m = 8;
printf("\n what is the highest mountain in the world?\n");
printf(" options\n");
printf(" 1.Mount Everest\n 2.Kangchenjunga \n 3.Annapurna\n 4.K2 \n");
scanf("%d", &b);
if (b != 1)
{
b = 3;
wrong();
beg8();
}
else
{
while (b == 1)
{
if (b == 1)
{
right();
beg8();
break;
}
}
}
}
void beg8()
{
int b;
m = 9;
printf("\n who invented piano?\n");
printf(" options\n");
printf(" 1.serin thomas\n 2.Bartolomeo Cristofori \n 3.annrose pino\n 4.Baldwin pinero \n");
scanf("%d", &b);
if (b != 2)
{
b = 3;
wrong();
beg9();
}
else
{
while (b == 2)
{
if (b == 2)
{
right();
beg9();
break;
}
}
}
}
void beg9()
{
int b;
m = 10;
printf("\n what is the answer of ( 3-3 x 6+2 )?\n");
printf(" options\n");
printf(" 1.-17\n 2. 0 \n 3. -13\n 4. 9 \n");
scanf("%d", &b);
if (b != 3)
{
b = 1;
printf("\n Do you want to know the correct answer for the qustion :\n1.yes\n2.no\t: ");
scanf("%d", &opt);
if (opt == 1)
{
printf("\n The correct answer is as follows:\n Question: 3 – 3 x 6 + 2\n Multiplication first : 3 – 18 + 2\n Left to right : -15 + 2\n Answer : -13\n");
}
wrong();
beg10();
}
else
{
while (b == 3)
{
if (b == 3)
{
right();
beg10();
break;
}
}
}
}
void beg10()
{
int len,i,f;
store_a();
printf("\n A man has a barrel with filled with oil that weighs 100 pounds,\n and then he puts something into it.\n Now the barrel weighs less than 100 pounds.\n What did he put in the barrel ?? \n");
printf(" enter the answer :");
scanf("%s", b);
len = strlen(b);
for (i = 0; i < len; i++)
{
if (a[i] == b[i])
{
f = 1;
}
else
{
f = 0;
break;
}
}
if (f == 1)
{
printf("The answer is correct!!\n");
the_end();
}
else
{
printf(" Wrong answer\nthe correct ans was 'hole'\n");
the_end();
}
}
void wrong()
{
printf("wrong answer !!\n");
printf("your score is :%d\n", i);
printf("\n qustion number: %d", m);
}//when the option is wrong
void the_end()
{
printf("\n***congratulations***\n");
printf(" your final score is :%d\n", i);
}//at the end of the game
void right()
{
printf("the answer is correct !!\n");
i++;
printf("your score is :%d\n", i);
printf("\n qustion number: %d", m);
}//when the ans is correct
void help()
{
int opt;
printf("\n 1.How to play\t2.About\t3.Main menu\n");
printf(" enter your option : ");
scanf("%d", &opt);
if (opt == 1)
{
printf(" answer the qustions..\n you get 1 point for each qustion..\n there is a total of 10 qustions try to get the maximum marks\n good luck \n");
help();
}
else if (opt == 2)
{
printf("\tCREATED BY\n **STEVEN THOMAS** \n **steventhomaspuli#gmail.com**\n ");
help();
}
else if (opt == 3)
{
main();
}
}//help menu
void store_a()
{
a[0] = 'h';
a[1] = 'o';
a[2] = 'l';
a[3] = 'e';
}
and this is the setup file I created
click here to download
pls tell me what is wrong here
You had built and shipped debug version of your program. Debug VC runtime is not a part of VC redistributable package, so your friend get a message about missing DLLs. Build and ship release version.

Function call not working in a function

#include<stdio.h>
void clearKeyboard(void){
while(getchar()!='\n');
}
void pause(void){
printf("Press <ENTER> to continue...");
clearKeyboard();
}
void printWelcome(void){
printf ("---=== Grocery Inventory System ===---\n\n");
}
int getInt(void){
int iVal;
char charCheck='x';
while (charCheck != '\n'){
scanf ("%d%c",&iVal,&charCheck);
if ( charCheck != '\n'){
clearKeyboard();
printf ("Invalid integer, please try again: ");
}
}
return iVal;
}
int getYesOrNo(void){
//list of variables declared and initialized
char ch;
int ret;
ch = 0;
ret = 0;
//it will keep asking the user as long as they don't reply with y or n
while(ch != 'Y' || ch != 'y' || ch != 'N' || ch != 'n')
{
scanf(" %c", &ch);
clearKeyboard();
if (ch == 'Y' || ch == 'y'){
ret = 1;
return ret;
}
else if (ch == 'N' || ch == 'n'){
ret = 0;
return ret;
}
//if they type other than y or n, it will print out this message
else{
printf("Only (Y)es or (N)o are acceptable: ");
}
}
return ret;
}
int getIntLimited(int lowerLimit, int upperLimit){
int iVal;
do{
iVal = getInt();
if (!(iVal >= lowerLimit && iVal <= upperLimit))
printf ("Invalid value, 0 <= value <= 7: ");
}while (!(iVal >= lowerLimit && iVal <=upperLimit));
return iVal;
}
int getMenuChoice(void){
int SEL;
int temp;
printf("1- List all items\n");
printf("2- Search by SKU\n");
printf("3- Checkout an item\n");
printf("4- Stock an item\n");
printf("5- Add new item or update item\n");
printf("6- delete item\n");
printf("7- Search by name\n");
printf("0- Exit program\n> ");
scanf("%d", &SEL);
if (SEL > 7){
temp = getIntLimited(0,7);
}
return SEL;
}
void GrocInvSys(void){
int SEL;
int DONE = 0;
SEL = 0;
printWelcome();
while (DONE == 0){
SEL = getMenuChoice();
clearKeyboard();
if (SEL == 1){
printf("List Items!\n");
pause();
}
if (SEL == 2){
printf("Search Items!\n");
pause();
}
if (SEL == 3){
printf("Checkout Item!\n");
pause();
}
if (SEL == 4){
printf("Stock Item!\n");
pause();
}
if (SEL == 5){
printf("Add/Update Item!\n");
pause();
}
if (SEL == 6){
printf("Delete Item!\n");
pause();
}
if (SEL == 7){
printf("Search by name!\n");
pause();
}
if(SEL == 0){
printf("Exit the program? (Y)es/(N)o): ");
DONE = getYesOrNo();
}
}
}
int main(void){
GrocInvSys();
return 0;
}
For this code, it would display all the items in the getMenuChoice and whenever use types the number for each item, it would print a special message.
Everything is working fine, however it should say "Invalid value, 0 < value < 7: " whenever I type something other than 0 or 1 or 2 or 3 or 4 or 5 or 6 or 7.
So I am guessing my getIntlimited function is not working in the getMenuChoice function. Any guesses to why?
p.s. I have typed pause(); for every if SEL == statement,is there any way I can make it better?
The main problem is some excess code in getMenuChoice(). It just needs to print the menu and return the value of getIntLimited(0,7):
int getMenuChoice(void){
printf("1- List all items\n");
printf("2- Search by SKU\n");
printf("3- Checkout an item\n");
printf("4- Stock an item\n");
printf("5- Add new item or update item\n");
printf("6- delete item\n");
printf("7- Search by name\n");
printf("0- Exit program\n> ");
return getIntLimited(0,7);
}
Another problem is the call to clearkeyboard() after the call to getMenuChoice() in GrocInvSys(). This reads more input up to the next newline, but getInt() has already read the newline that terminated the integer. There is no need to read another line, since its contents are just ignored. Remove that call to clearkeyboard() to fix that problem.

How would i make this program loop the main twice?

I need my program to create two different text files (midinotes1 & midinotes2) and store two bits of data inside them to be read later on. is there an efficient way without copying the code? i understand i need to have filepointer1 writing to midinotes1 and filepointer2 writing to midinotes2 but i dont know how to make my program do that?
Thanks for any advice!
#include "aservelibs/aservelib.h"
#include <stdio.h>
#include <math.h>
#include <string.h>
float mtof(int note, float frequency);
int main()
{
FILE *textFilePointer;
FILE *textFilePointer2;
int note;
int velocity;
int program;
int counter = 0;
char user;
float frequency;
do
{
printf("Press R to Record (R) or (X) to Exit: \n");
scanf(" %c", &user);
if (user == 'r' || user == 'R')
{
textFilePointer = fopen("/Users/Luke/Desktop/midinotes1.txt", "w");
counter = 0;
if (textFilePointer == NULL)
{
printf("Error Opening file.\n");
}
else
{
do
{
note = aserveGetNote();
velocity = aserveGetVelocity();
if (velocity > 0)
{
fprintf(textFilePointer, "%d\n, %d\n", note, velocity);
counter++;
}
program = aserveGetProgram();
} while (counter < 16);
fclose(textFilePointer);
}
}
else if(user == 'x' || user == 'X')
break;
} while(user != 'x' || user != 'X');
return 0;
}
float mtof(int note, float frequency)
{
frequency = 440.0 * pow(2, (note-69) / 12.0);
printf("%d\n", note);
return frequency;
}
int index = 0;
char filename[128];
do
{
printf("Press R to Record (R) or (X) to Exit: \n");
scanf(" %c", &user);
if (user == 'r' || user == 'R')
{
snprintf(filename, 120, "notes%d.txt", (index+1));
textFilePointer = fopen(filename, "w");
counter = 0;
if (textFilePointer == NULL)
{
printf("Error Opening file.\n");
}
else
{
do
{
// your work
} while (counter < 16);
fclose(textFilePointer);
index++;
}
}
else if(user == 'x' || user == 'X')
break;
} while(user != 'x' || user != 'X');
return 0;
int main()
{
FILE *textFilePointer;
char filename[100];
int note;
int velocity;
int program;
int counter = 0;
char user;
float frequency;
int sample = 0;
do
{
printf("Press R to Record (R) or (X) to Exit: \n");
scanf(" %c", &user);
if (user == 'r' || user == 'R')
{
sample++;
sprintf(filename, "/Users/Luke/Desktop/midinotes%d.txt", sample);
textFilePointer = fopen(filename, "w");
counter = 0;
if (textFilePointer == NULL)
printf("Error Opening file.\n");
else
{
do
{
note = aserveGetNote();
velocity = aserveGetVelocity();
if (velocity > 0)
{
fprintf(textFilePointer, "%d\n, %d\n", note, velocity);
counter++;
}
program = aserveGetProgram();
} while (counter < 16);
fclose(textFilePointer);
}
}
else if(user == 'x' || user == 'X')
break;
} while(user != 'x' || user != 'X');
return 0;
}

Resources