1
Hello; I have a code that should be done in the C language, which is to receive a numerical expression, including the result of it, for example: "20+30=50", which will be stored in a string. After receiving the expression, I wish to break up this expression by placing each number into an int variable, and the operators ("+" and "=", in this case) into char type variables and present each one separately in their respective int and char variables. I can do what I want by using only the first number ("20"), the first operator ("+") and the equality operator ("=") that I can store in the correct variables, the other numbers are empty. Following is my code for you to analyze and help me, it is not complete yet, I need to make this reading and "dismemberment" of the string work to complete the program. I’ve researched a lot of places, I’ve asked a lot of questions with a lot of people, and nothing’s been solved yet. Anyone who can point out the error, present me with a new solution, I will be very grateful.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char expressao[20];
int tamExpressao;
int aux1;
int aux2;
int aux3;
int aux4;
char num1[3]={0};
char num2[3]={0};
char num3[3]={0};
char oper1;
char operIgual;
int numero1=0;
int numero2=0;
int numero3=0;
printf("Digite expressao:\n");
scanf("%s", expressao);
printf("%s\n\n", expressao);
tamExpressao=strlen(expressao);
printf("%i\n\n", tamExpressao);
for (aux1=0; aux1<tamExpressao; aux1++)
{
if (expressao[aux1]=='0'|expressao[aux1]=='1'|expressao[aux1]=='2'|expressao[aux1]=='3'|expressao[aux1]=='4'|expressao[aux1]=='5'|expressao[aux1]=='6'|expressao[aux1]=='7'|expressao[aux1]=='8'|expressao[aux1]=='9')
{
for (aux2=0; aux2<3; aux2++)
{
if (numero1>0)
{
if (numero2>0)
{
num3[aux2]=num3[3]+expressao[aux1];
} else {num2[aux2]=num2[3]+expressao[aux1];}
} else {num1[aux2]=num1[3]+expressao[aux1];}
}
} else if (expressao[aux1]=='+'|expressao[aux1]=='-')
{
numero1=atoi(&num1[aux2]);
oper1=expressao[aux1];
} else if (expressao[aux1]=='=')
{
numero2=atoi(&num2[aux2]);
operIgual=expressao[aux1];
}
}
numero3=atoi(&num3[3]);
//Apresentação dos números digitados
printf("%i\t%i\t%c\t%i\t%c\t%i\n", aux1, numero1, oper1, numero2, operIgual, numero3);
//---
system("PAUSE");
return 0;
}
Can’t you format the code a little better? You don’t even want to touch something like that. It helps you not understand what you’re doing. I was trying to read and got lost in it.
– Maniero
Consider using
strtoull()
Vz deatoi()
. With the first function get a much more powerful error handling.– pmg
Use
||
and&&
(short circuit operators) instead of|
and&
in your ifs. Also, it has a ctype header. h with functions like isdigit and isspace that are useful for you (and more efficient than your ifs as well)– hugomg