I'm doing a homework problem which is to create a calculator using the argc and argv[] parameters in the main function.
What we were supposed to do, and I did, was to create a char pointer array containing the operators I want to use.
this is what I have:
const int OTabMax = 10;
const char *OTab[] = {
"+",
"-",
"*",
"/",
"quad",
"wurz",
"sinR",
"sinG",
"cosR",
"cosG"
};
int OTabCheck(char S[]) // char *S
{
int n;
for (n = 0; n < OTabMax; n++){
if (strcmp(S, OTab[n]) == 0) {break;}
}
return n;
}
It returns a number depending on which operator was used, which goes into a switch case where the calculation is done.
looks like this:
switch(key){
case 0:
break;
case 1:
break;
case 2:
x = atof(argv[1]);
y = atof(argv[3]);
z = 0;
z = x*y;
printf("%f * %f = %f\n",x,y,z);
break;
case 3-8;
break;
case 9:
break;
default: printf("Wrong input!\n"); exit(0); break;
}
The case in question is case 2: which whenever I do a calculation like calling the program through the terminal with ./"program_name" 2 * 2
it printf's 2.000000 * 0.000000 = 2.000000
here is the MRE:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
const int OTabMax = 10;
const char *OTab[] = {
"+",
"-",
"*",
"/",
"quad",
"wurz",
"sinR",
"sinG",
"cosR",
"cosG" };
int OTabCheck(char S[]) // char *S
{
int n;
for (n = 0; n < OTabMax; n++){
if (strcmp(S, OTab[n]) == 0) {break;}
}
return n;
}
int main(int argc,char *argv[]){
float x = 0;
float y = 0;
float z = 0;
int key = 0;
if(argc < 3){
exit(0);
}
if(argc == 4){
key = OTabCheck(argv[2]);
}else if(argc == 3){
key = OTabCheck(argv[1]);
}
switch(key){
case 2:
x = atof(argv[1]);
y = atof(argv[3]);
z = 0;
z = x*y;
printf("%f * %f = %f\n",x,y,z);
exit(0);
break;
default: printf("Wrong input!\n"); exit(0); break;
}
}
Related
I'm trying to make a program that will print all the prime number between 2 values (lvan (lower value) and uval (upper value)), print some of them by the user choice (nval) and will find them by using number of child processes (pval is the number of children's).
so the problem is that I don't know how to make my program make only the asked amount of child processes and preventing my child process from creating it's own childs.
I will mark the line that I thought that I need to enter the code that will make everything work well (may be a wrong line).
I've tried to kill the child process but that's terminated all the program, I've tried to make the child return a value (with return and exit commands) but that terminated the program as well.
What should I do ?
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/mman.h>
#include <sys/wait.h>
void parseargs(char *argv[], int argc, int *lval, int *uval, int *nval, int *pval);
int isprime(int n);
int countFlags(char* arr, int size);
int main (int argc, char **argv)
{
int lval = 1; //def val
int uval = 100; //def val
int nval = 10; //def val
int pval = 4; //def val
int count = 0;
int rc,num;
// Parse arguments
parseargs(argv, argc, &lval, &uval, &nval, &pval);
if (uval < lval)
{
fprintf(stderr, "Upper bound should not be smaller then lower bound\n");
exit(1);
}
if (lval < 2)
{
lval = 2;
uval = (uval > 1) ? uval : 1;
}
if (pval < 0)
pval=4;
char *flagarr = mmap ( NULL, (uval-lval+1)*sizeof(char),
PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_SHARED, -1, 0 );
if (flagarr == MAP_FAILED)
exit(2);
//start forks
for(int i =0; (i<pval); i++){
if(rc=fork()<0)
{
printf("fork failed");
exit(1);
}
if(rc==0)
{
for (num = lval+i; num <= uval; num+=pval)
{
if (isprime(num))
{
flagarr[num - lval] = 1;
count ++;
} else {
flagarr[num - lval] = 0;
}
}
printf("%d\n",i);
//problematic line imo ??
}
}
for(int i =0; (i<pval) ; i++)
wait(NULL);
// Print results
printf("Found %d primes%c\n", count, count ? ':' : '.');
for (num = lval; (num <= uval) && (nval) ; num++)
if (flagarr[num - lval])
{
nval--;
count--;
printf("%d%c", num, (count && nval) ? ',' : '\n');
}
munmap(flagarr,(uval-lval+1));
return 0;
}
// NOTE : use 'man 3 getopt' to learn about getopt(), opterr, optarg and optopt
void parseargs(char *argv[], int argc, int *lval, int *uval, int *nval, int *pval)
{
int ch;
opterr = 0;
while ((ch = getopt (argc, argv, "l:u:n:p:")) != -1)
switch (ch)
{
case 'l': // Lower bound flag
*lval = atoi(optarg);
break;
case 'u': // Upper bound flag
*uval = atoi(optarg);
break;
case 'n':
*nval = atoi(optarg);
break;
case 'p':
*pval = atoi(optarg);
break;
case '?':
if ((optopt == 'l') || (optopt == 'u')|| (optopt == 'n')|| (optopt == 'p'))
fprintf (stderr, "Option -%c requires an argument.\n", optopt);
else if (isprint (optopt))
fprintf (stderr, "Unknown option `-%c'.\n", optopt);
else
fprintf (stderr, "Unknown option character `\\x%x'.\n", optopt);
exit(1);
default:
exit(1);
}
}
int countFlags(char* arr, int size)
{
int ret =0;
for(int i=0;i<size;i++)
ret+=arr[i];
return ret;
}
int isprime(int n)
{
static int *primes = NULL; // NOTE: static !
static int size = 0; // NOTE: static !
static int maxprime; // NOTE: static !
int root;
int i;
// Init primes array (executed on first call)
if (primes == NULL)
{
primes = (int *)malloc(2*sizeof(int));
if (primes == NULL)
exit(1);
size = 2;
primes[0] = 2;
primes[1] = 3;
maxprime = 3;
}
root = (int)(sqrt(n));
// Update primes array, if needed
while (root > maxprime)
for (i = maxprime + 2 ; ; i+=2)
if (isprime(i))
{
size++;
primes = (int *)realloc(primes, size * sizeof(int));
if (primes == NULL)
exit(1);
primes[size-1] = i;
maxprime = i;
break;
}
// Check 'special' cases
if (n <= 0)
return -1;
if (n == 1)
return 0;
// Check prime
for (i = 0 ; ((i < size) && (root >= primes[i])) ; i++)
if ((n % primes[i]) == 0)
return 0;
return 1;
}
This is my code the only thing I can do is quit. There are two functions one where it calculates Fahrenheit to Celsius and the other does the opposite and there is an array that stores the data as well. Then I added the switch at the end. I understand each concept individually but don't know how to bring them together.
#include <stdlib.h>
#define SIZE 1
//C = (5 / 9) * (F - 32) and F = (9 / 5) * C + 32
// calculate f to c
int getValue() {
int result;
printf("Input degree: ");
scanf_s("%i", &result);
return result;
}
int F (int input[], int size) {
int result = 0;
int a;
for (a = 0; a = size; a++) {
if (input[a] = result);
result = (9 / 5) * input[a] + 32;
}
return result;
}
int C (int input[], int size) {
int result = 0;
int a;
for (a = 0; a = size; a++) {
if (input[a] = result);
result = (5 / 9) * (input[a] - 32);
}
return result;
}
main() {
int choice;
int input[SIZE];
int F, C;
int a;
for (a = 0; a < SIZE; a++) {
input[a] = getValue();
F = (input, SIZE);
C = (input, SIZE);
}
do {
printf("Welcome to the Main Menu\n");
printf("1. Convert temperature input from the user in degrees Fahrenheit to degrees Celsius\n");
printf("2. Convert temperature input from the user in degrees Celsius to degrees Fahrenheit\n");
printf("3. Quit.\n");
scanf_s("%i", &choice);
} while (choice != 3);
switch (choice) {
case 1:
printf("%i degree C\n", F);
break;
case 2:
printf(" % i degree F\n", C);
break;
case 3:
printf("You have chosen option 3 you are now able to quit\n");
break;
}
system("pause");
}```
Beside the errors pointed in the answer by #Mehmet Aslan, you should move the switch block into the while loop, so it gets executed each time the user selects an option. As it is now, it will only be run once, when the user has chosen the option "3"
Since this looks like homework here is constructive feedbacks. Hopefully you ll manage.
Hints:
Look into pointers
int getValue();
void F(int *output, int *input, int size);
void C(int *output, int *input, int size)
{
for(int i = 0; i < size; ++i)
{
output[i] = (5 / 9) * (input[i]- 32);
}
}
#include <stdlib.h>
#define SIZE 1
//C = (5 / 9) * (F - 32) and F = (9 / 5) * C + 32
// calculate f to c
int getValue() {
int result;
printf("Input degree: ");
scanf_s("%i", &result);
return result;
}
int F (int input[], int size) {
int result = 0;
int a;
for (a = 0; a = size; a++) {
if (input[a] = result);
result = (9 / 5) * input[a] + 32;
}
return result;
}
int C (int input[], int size) {
int result = 0;
int a;
for (a = 0; a = size; a++) {
if (input[a] = result);
result = (5 / 9) * (input[a] - 32);
}
return result;
}
main() {
int choice;
int input[SIZE];
int F, C;
int a;
for (a = 0; a < SIZE; a++) {
input[a] = getValue();
F = (input, SIZE); <<---compile time error, not a function call
C = (input, SIZE); <<---compile time error, not a function call
}
// F(output, input, SIZE) <<--- it should be here, so you could calculate after collect inputs
do {
printf("Welcome to the Main Menu\n");
printf("1. Convert temperature input from the user in degrees Fahrenheit to degrees Celsius\n");
printf("2. Convert temperature input from the user in degrees Celsius to degrees Fahrenheit\n");
printf("3. Quit.\n");
scanf_s("%i", &choice);
} while (choice != 3);
switch (choice) {
case 1:
printf("%i degree C\n", F); <<---F compile time error, not a function call
break;
case 2:
printf(" % i degree F\n", C); <<---C compile time error, not a function call
break;
case 3:
printf("You have chosen option 3 you are now able to quit\n");
break;
}
system("pause");
}
I'm writing a function that receives a format normally seen in a printf call and a string of integers separated by an inconsistent amount of spaces. It prints the format how it would've been printed from printf with the correct representation of the integers.
I first tried to create the extractNums function that returns an array of all the integers from the second string sent to the printFormattedIntegers function.
But later in printFormattedIntegers I get a Exception: EXC_BAD_ACCESS (code=EXC_I386_GPFLT error when I simply try to print the first element of the format string. I found that if I comment out the extractNums function call, I get no error and it works.
I'm not sure why the extractNums call interrupts the rest of the program, any ideas?
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define I 1
#define V 5
#define X 10
#define L 50
#define C 100
#define D 500
#define M 1000
void printFormattedIntegers(char* format, char numbers[]);
char converter(char c, int num);
int charToInt(char* str);
int* extendArr(int* arr, int currSize);
int* extractNums(char* nums);
void printDecAsBin(int num);
void printDEC(int num);
void printHEX(int num);
void printOCT(int num);
void printBIN(int num);
void printROM(int num);
void main()
{
char format[100];
char numbers[100];
printFormattedIntegers("Dec: %d Hex: %x Roman: %r", " 123 10 9");
}
void printFormattedIntegers(char* format, char* numbers)
{
int formatInd = 0, numsInd = 0;
int* numsArr = extractNums(numbers);
while (format[formatInd] != '\0')
{
if (format[formatInd] != '%')
printf("%c",format[formatInd]);
else
{
converter(format[formatInd+1], numsArr[numsInd]);
numsInd++;
}
formatInd++;
}
}
char converter(char c, int num)
{
switch(c)
{
case 'd':
printDEC(num);
break;
case 'x':
printHEX(num);
break;
case 'o':
printOCT(num);
break;
case 'b':
printBIN(num);
break;
case 'r':
printROM(num);
break;
case '\0':
printf("%%");
break;
default:
printf("%%%c",c);
break;
}
}
int charToInt(char* str)
{
int mult = 1;
int re = 0;
int len = strlen(str);
for(int i = len -1 ; i >= 0 ; i--)
{
re = re + ((int)str[i] -48)*mult;
mult = mult*10;
}
return re;
}
int* extendArr(int* arr, int currSize)
{
int* newArr;
int i;
newArr = (int*)malloc((currSize+1) * sizeof(int));
if (newArr == NULL)
{
printf("Memory allocation failed.\n");
exit(1);
}
for (i=0;i<currSize;i++)
newArr[i] = arr[i];
free(arr);
return newArr;
}
int* extractNums(char* nums)
{
char *copiedStr, *token;
int *newArr=NULL,counter = 0, intChar;
char sep[] = " ";
strcpy(copiedStr,nums);
token = strtok(copiedStr,sep);
while (token != NULL)
{
intChar = charToInt(token);
newArr = extendArr(newArr,counter);
newArr[counter] = intChar;
counter++;
token = strtok(NULL,sep);
}
}
void printDecAsBin(int num)
{
if (num == 0)
printf("0");
else if (num == 1)
printf("1");
else
{
printDecAsBin(num / 2);
printf("%d", num % 2);
}
}
void printDEC(int num)
{
printf("%d", num);
}
void printHEX(int num)
{
printf("%x", num);
}
void printOCT(int num)
{
printf("%o", num);
}
void printBIN(int num)
{
printDecAsBin(num);
}
void printROM(int num)
{
while (num >= M)
{
num -= M;
printf("M");
}
if (num >= M - C)
{
printf("CM");
num -= (M - C);
}
else if (num >= D)
{
printf("D");
num -= D;
}
while (num >= C)
{
num -= C;
printf("C");
}
if (num >= C - X)
{
printf("XC");
num -= (C - X);
}
else if (num >= L)
{
printf("L");
num -= L;
}
while (num >= X)
{
num -= X;
printf("X");
}
if (num >= X - I)
{
printf("IX");
num -= (X - I);
}
else if (num >= V)
{
printf("V");
num -= V;
}
while (num > 0)
{
num -= I;
printf("I");
}
}
You are writing to unallocated memory. That invokes Undefined Behaviour and from that point anything can happen at any moment:
int* extractNums(char* nums)
{
char *copiedStr, *token; // copiedStr is an initialized pointer here
int *newArr=NULL,counter = 0, intChar;
char sep[] = " ";
strcpy(copiedStr,nums); // use of the initialized pointer: UB!
I am getting a "Type mismatch in parameter 1 in call to 'push'" error at the 28th line of the code in Turbo C++, please help me as I have to submit my project, I know that Turbo C++ is a very old compiler but that's what our University Teacher recommends so I cant do nothing in that
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
#include <stdio.h>
#include <conio.h>
int stack[100];
int top = -1;
void in2post(char[]);
void push(int);
int pop();
int prec(char);
int cal(char[]);
void main()
{
char in[100], post[100];
clrscr();
printf("Enter an infix expression: ");
gets(in);
in2post(in);
getch();
}
void in2post(char in_exp[])
{
int x = 0, y = 0, z, result = 0;
char a, c, post_exp[100];
char t;
push("\0");
t = in_exp[x];
while (t != '\0')
{
if (isalnum(t))
{
post_exp[y] = t;
y++;
}
else if (t == '(')
{
push('(');
}
else if (t == ')')
{
while (stack[top] != '(')
{
c = pop();
post_exp[y] = c;
y++;
}
c = pop();
}
else
{
while (prec(stack[top]) >= prec(t))
{
c = pop();
post_exp[y] = c;
y++;
}
push(t);
}
x++;
t = in_exp[x];
}
while (top != -1)
{
c = pop();
post_exp[y] = c;
y++;
}
printf("\nThe equivalent postfix expression is: ");
for (z = 0; z < y; z++)
printf("%c", post_exp[z]);
printf("\n\nDo you want to evaluate the postfix expression? (Y/N): ");
scanf("%c", &a);
if (a == 'y' || a == 'y')
{
result = cal(post_exp);
printf("\nResult = % d\n", result);
getch();
}
else if (a == 'n' || a == 'N')
{
exit(0);
}
}
int cal(char post[])
{
int m, n, x, y, j = 0, len;
len = strlen(post);
while (j < len)
{
if (isdigit(post[j]))
{
x = post[j] - '0';
push(x);
}
else
{
m = pop();
n = pop();
switch (post[j])
{
case '+':
x = n + m;
break;
case '-':
x = n - m;
break;
case '*':
x = n * m;
break;
case '/':
x = n / m;
break;
}
push(x);
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
first of all, I understand mostly everything in this program that I copied from this book.
second, i just wanted to see if it worked ,
the only problem is that it says 'expected declaration specifiers before 'main''
and i don't know what it means
ps this is a really long program (300+ lines)
#include <stdio.h>
#include <time.h>
#include <ctype.h>
#include <stdlib.h>
#define FALSE 0
#define TRUE 1
void printGreeting();
int getBet();
char getSuit(int suit);
char getRank(int rank);
void getFirstHand(int cardRank[], int cardSuit[]);
void getFinalHand
(int cardRank[], int cardSuit[], int finalRank[], int finalSuit[], int
ranksinHand[], int suitsinHand[])
int analyzeHand(int ranksinHand[], int suitsinHand[]);
main()
{
int bet;
int bank = 100;
int i;
int cardRank [5];
int cardSuit [5];
int finalRank[5];
int finalSuit[5];
int ranksinhand[13];
int suitsinhand[4];
int winnings;
time_t t;
char suit, rank, stillPlay;
printGreeting();
do{
bet = getBet();
srand(time(&t));
getFirstHand(cardRank, cardSuit);
printf("Your five cards: \n\n");
for (i = 0; i < 5; i++)
{
suit = getSuit(cardsSuit[i]);
rank = getRank(cardRank[i]);
printf("Card #%d: %c%c\n\n", i+1, rank, suit);
}
for (i=0; i < 4; i++)
{
suitsinHand[i] = 0;
}
for (i=0; i < 13; i++)
{
ranksinHand[i] = 0;
}
getFinalHand(cardRank, cardSuit, finalRank, finalSuit, ranksinHand,
suitsinHand);
printf("Your five final cards:\n\n");
for (i = 0; i < 5; i++)
{
suit = getSuit(finalSuit[i]);
rank = getRank(finalRank[i]);
printf("Card #%d: %c%c\n\n", i+1, rank, suit);
}
winnings = analyzeHand(ranksinHand, suitsinHand);
printf("You won %d!\n\n", bet*winnings);
bank = bank - bet + (bet*winnings)
printf("\n\nYour bank is now %d.\n\n", bank);
printf("Want to play again? ");
scanf(" %c", &stillPlay);
}while (toupper(stillPlay) == 'Y');
return;
}
/*************************************************************************/
void printGreeting();
{
printf("**********************************************************\n\n");
printf("\n\n\tWelcome to the Absolute Beginner's Casino\n\n");
printf("\tHome of the Video Draw Poker");
printf("**********************************************************\n\n");
printf("Here are the rules\n");
printf("You start with 100 credits, and you make a bet from");
printf("1 to 5 credits.\n");
printf("You are dealt 5 cards, and then you choose which ");
printf("cards to keep");
printf("or discard\n");
printf("You want to make the best possible hand.\n");
printf("\nHere is the table for winnings (assuming a ");
printf("bet of 1 credit):");
printf("\nPair \t\t\t\t1 credit");
printf("\nTwo pairs\t\t\t2 credits");
printf("\nThree of a kind\t\t\t3 credits");
printf("\nStraight \t\t\t4 credits");
printf("Flush\t\t\t\t5 credits");
printf("Full House\t\t\t8 credits");
printf("Four of a Kind\t\t\t10 credits");
printf("Straight Flush\t\t\t20 credits");
printf("\n\nHave fun!!\n\n");
}
void getFirstHand(int cardRank[], int cardSuit[]);
{
int i,j;
int carDup;
for(i=0; i < 5; i++)
{
carDup = 0;
do{
cardRank[i] = (rand() % 13);
cardSuit[i] = (rand() % 4);
for (j=0; j < i; j++)
{
if ((cardRank[i] == cardRank[j] &&
cardSuit[i] == cardSuit[j]))
{
carDup = 1;
}
}
}while (carDup == 1;);
}
}
char getSuit(int suit)
{
switch
{
case 0:
return('C');
case 1:
return('D');
case 2:
return('H');
case 3:
return('S');
}
}
char getRank(int rank)
{
switch (rank)
{
case 0:
return('A');
case 1:
return('2');
case 2:
return('3');
case 3:
return('4');
case 4:
return('5');
case 5:
return('6');
case 6:
return('7');
case 7;
return('8');
case 8:
return('9');
case 9:
return('T');
case 10:
return('J');
case 11:
return('Q');
case 12:
return('K');
}
}
int getBet()
{
int bet;
do
{
printf("How much do you want to bet?(Enter a number");
printf("from 1 to 5, or 0 to quit the game): ");
scanf(" %d", &bet);
if (bet >= 1 && bet <= 5)
{
return(bet);
}
else if (bet == 0)
{
exit(1);
}
else
{
printf("\n\nPlease enter a bet from 1-5 or ");
printf("0 to quit the game\n\n");
}
}while ((bet < 0) || (bet > 5));
}
int analyzeHand(int ranksinHand[], int suitsinHand[])
{
int num_consec = 0;
int i, rank, suit;
int straight = FALSE;
int flush = FALSE;
int four = FALSE;
int three = FALSE;
int pairs = 0;
for (suit = 0; suit < 4; suit++)
if (suitsinHand[suit] == 5)
flush = TRUE;
rank = 0;
while (ranksinHand[rank] == 0)
rank++;
for (; rank < 13 && ranksinHand[rank]; rank++)
num_consec++;
if(num_consec == 5) {
straight = TRUE;
}
for (rank = 0; rank < 13; rank++){
if (ranksinHand[rank] == 4)
four == TRUE;
if (ranksinHand[rank] == 3)
three == TRUE;
if (ranksinHand[rank] == 2)
pairs++;
}
if (straight && flush){
printf("Straight Flush\n\n");
return(20);
}
else if (four){
printf("Four of a kind\n\n");
return (10);
}
else if (three && pairs == 1){
printf("Full House\n\n");
return (8);
}
else if (flush){
printf("Flush\n\n");
return (5);
}
else if (straight){
printf("Straight\n\n");
return (4);
}
else if (three){
printf("Three of a Kind\n\n");
return (3);
}
else if (pairs == 2){
printf("Two Pairs\n\n");
return (2);
}
else if (pairs == 1){
printf("Pair\n\n");
return (1);
}
else{
printf("High Card\n\n");
return (0);
}
}
void getFinalHand
(int cardRank[], int cardSuit[], int finalRank[], int finalSuit[], int
ranksinHand[], int suitsinHand[])
{
int i, j, carDup;
char suit, rank, ans;
for (i=0; i < 5; i++)
{
suit = getSuit(cardSuit[i]);
rank = getRank(cardRank[i]);
printf("Do you want to keep card #%d: %c%c", i+1, rank, suit);
printf("\nPlease answer (Y/N):");
scanf(" %c", &ans);
if (toupper(ans) == 'Y')
{
finalRank[i] = cardRank[i];
finalSuit[i] = cardSuit[i];
ranksinHand[finalRank[i]]++;
suitsinHand[finalSuit[i]]++;
continue;
}
else if (toupper(ans) == 'N')
{
carDup = 0;
do{
carDup = 0;
finalRank[i] = (rand() % 13);
finalSuit[i] = (rand() % 4);
for (j=0; j < 5; j++)
{
if((finalRank[i] == finalRank[j]) && (finalSuit[i] ==
finalSuit[j]))
{
carDup = 1;
}
}
for (j=0; j < i; j++)
{
if((finalRank[i] == finalRank[j]) && (finalSuit[i] ==
finalSuit[j]))
{
carDup = 1;
}
}
}while (carDup == 1);
ranksinHand[finalRank[i]]++;
suitsinHand[finalSuit[i]]++;
}
}
}
By convention main() must return an integer. You have to declare it like that:
int main()
{
// Your method
return 0;
}
int mainor
void main
would do the work. Here, int main is shown to be the C standard. Refer to
Return type of main() too.