Sorry if the title is not clear about what I want to achieve.
So let me explain:
I'm trying to make a calculator that can enable the use of variables that are each labeled with a lowercase letter. All lowercase letters should be usable (a-z, each with value storage). The following should be possible:
Assignment of a value in a variable, example: a = 1
Use of a variable in an invoice with direct output, example: 3 + a
Assignment of an invoice result into a variable, examples: b = 3 + 1 or c = 6 * b
For clarification again, for example the following inputs should be possible:
x=3 // Variable x receives value 3
d=9 // Variable d gets value 9
3*5 // Output result
h=9/3 // Variable h gets value Result of calculation 9/3
x * h // Output result of calculation x*h, because x=3 and h=3, output 9
i=d/x // variable i gets value from calculation, so 9/3, output result 3
I'm not looking for code snipets per se but more for a way to apprehend the problem.
Thank you in advance for any help!
This is what I did so far:
int main(void) {
int weiter = 1;
do {
char eingabe[21];
int zahl1 = 0;
int zahl2 = 0;
int ergebnis = 0;
char op = ' ';
int retval = 0;
retval = scanf("%s", &eingabe);
printf("retval = %d\n", retval);
printf("eingabe[0] = %c\n", eingabe[0]);
// fall2 zahl opo char
char *peingabe = &(eingabe[0]);
printf("peingabe = %c\n", *peingabe);
char *temp = strpbrk(peingabe, "+-*/=");
op = *temp;
printf("Op = %c\n", op);
temp = strtok(peingabe, "+-*/");
printf("1.temp = %s\n", temp);
zahl1 = atoi(temp);
printf("Zahl_1 = %d\n", zahl1);
temp = strtok(NULL, "+-*/");
printf("2.temp = %s\n", temp);
zahl2 = atoi(temp);
printf("Zahl_2 = %d\n", zahl2);
// fall3 char gleich zahl
// fall4 char op zahl
// fall5 char op char
// fall6 char=zahl op zahl
// fall7 char=char op zahl
// fall8 char=zahl op char
// fall9 char=char op char
// fall10 char gleich char
switch (op) {
case '+':
ergebnis = zahl1 + zahl2;
printf("Sum = %d\n", ergebnis);
break;
case '-':
ergebnis = zahl1 - zahl2;
printf("Sum = %d\n", ergebnis);
break;
case '*':
ergebnis = zahl1 * zahl2;
printf("Sum = %d\n", ergebnis);
break;
case '/':
ergebnis = zahl1 / zahl2;
printf("Sum = %d\n", ergebnis);
break;
default:
printf("Error\n");
weiter = 0;
break;
}
} while (weiter > 0);
return 0;
}
Your calculator appears to be processing a line of text and so it will need to sample each character in order to determine how to handle it, maybe by use of a switch statement.
If you read a numerical character e.g., in the range 0 to 9, then you append or add it to a temporary storage char array so that you can convert it to a numerical value later.
If you detect a letter within the ASCII range a to z, then that is your variable.
Just remember to clear the temporary storage locations when no longer required.
To handle your variables, I would create an array of the largest signed values that you expect to calculate then index these based upon the ASCII value of the variable letter starting with a being an index of zero, z being 25. ASCII a has a value of 97, z has a value of 122
Related
I want to make a calculator that is capable of calculation with decimal numbers and is able to return the decimal values in their respective binary, octal or hexadecimal representation.
So far in the main method the program reads the command line and I can invoke the program by two ways.
The first way would be with 3 values:
"number1" "operator" "number2".
And the second way would be with 4 values:
"wished numeral system for the output" "number1" "operator" "number2".
Where for the wished numeral system output b would stand for for binary, o for octal and h for hexadecimal. In both ways the user should be able to input decimal, octal and hexadecimal numbers for the inputs number1 and number2.
#include "zahlen.h"
#include <stdio.h>
#include "stringTOint.h"
int main(int argc, char *argv[]) {
char o,op,sx[DIGITS+1],sy[DIGITS+1],sz[DIGITS+1];
int x,y,z;
char flag_x,flag_y;
/* 1) Read Commandline */
if (argc != 4 && argc != 5) {
printf("Aufruf: %s -o <x> <op> <y> \n",argv[0]);
return 1;
} else if(argc == 4) {
x = stringTOint(argv[1]);
op = argv[2][0];
y = stringTOint(argv[3]);
} else if(argc == 5) {
o = argv[1][0];
x = stringTOint(argv[2]);
op = argv[3][0];
y = stringTOint(argv[4]);
if(o != 'b' && o != 'o' && o != 'h') {
printf("Wrong Operation\n");
return 1;
}
}
/* 2) Solve the equation */
if(argc==4) {
printf("solve: %s %c %s \n", argv[1], op, argv[3]);
z = solve(x, op, y);
} else if(argc==5) {
printf("solve: %s %c %s \n", argv[2], op, argv[4]);
z = solve(x, op, y);
}
/* 3) Calculate the Representation of the wished Numeral System */
switch(o) {
case 'b':
intTObinaer(x, sx);
intTObinaer(y, sy);
intTObinaer(z, sz);
break;
case 'o':
intTOoctal(x,sx);
intTOoctal(y,sy);
intTOoctal(z,sz);
break;
case 'h':
intTOhexal(x,sx);
intTOhexal(y,sy);
intTOhexal(z,sz);
break;
default:
intTObinaer(x, sx);
intTObinaer(y, sy);
intTObinaer(z, sz);
break;
}
/* 4) Return the results */
printf("\n %s %d\n%c %s %d\n= %s %d\n", sx,x,op,sy,y,sz,z);
return 0;
}
The methods intTObinaer, intTOoctal and intTOhexal only differ by the base with which the decimal number gets divided.
intTObinaer(int i, char str[]) {
unsigned int zahl = i;
int j;
/* Fill Array with zeros */
int x = 0;
for (x; x < DIGITS+1; x++) {
str[x] = '0';
}
/*Calculate the Binary representation of the given Decimal integer */
for (j = DIGITS-1; j > 0; j--) {
/* This base gets changed to 8 or 16 for octal and hexal representation */
str[j] = (char) (zahl % 2) + '0';
zahl = zahl / 2;
if (zahl == 0) {
break;
}
}
/* Set the end of the Array */
str[DIGITS] = '\0';
}
The actual equation gets solved in the solve method, where the right operation for number1 and number2 gets chosen by an switchcase where the different cases can be selected by the char op that the user had input between the two numbers.
#include <stdio.h>
int solve(int x, char op, int y) {
int ergebnis = 0;
switch(op) {
case '+':
ergebnis = x + y;
break;
case '-':
ergebnis = x - y;
break;
case '*':
ergebnis = x * y;
break;
case '/':
ergebnis = x / y;
break;
case '&':
ergebnis = x & y;
break;
case '|':
ergebnis = x | y;
break;
default:
printf("Wrong input\n");
}
return ergebnis;
}
My question now is due to the fact the the user should be able to input different numeral systems(e.g. decimal, octal or hexadecimal) how can I identify the different numeral systems and then transfer them into decimal so that I can calculate the result. After that these decimal Numbers have to be converted back into the desired numeral system that the user wanted.
Looks like you only need to add two lines to do that:
#include "stdlib.h"
#define stringTOint(arg) ((int)strtol(arg,NULL,0))
Or better yet, replace those invocations of stringTOint() with corresponding strtol() invocations (and add the #include, of course).
strtol() uses the same prefixes as for C literals: 0 for octal, 0x for hex, no prefix is decimal.
I would like to suggest another approach to this problem.
Many of the parsing you perform can be performed directly by the sscanf function, the only case is the binary case that needs to be implemented differently.
The implementation follows 3 main step:
Parse the input using the sscanf function (or the ConvCharToBinfor binary values) and store the values in the variables a and b;
Perform the operation and store the result in the res variable;
Print the output result by using the printf parsing (or loop for the binary case).
An implementation would be the following:
#include<stdio.h>
#include<string.h>
typedef struct stack {
unsigned char data[32];
int size;
} stack_t;
int ConvCharToBin(char* input);
int main(int argc, char *argv[]) {
char numSys = 'd', op;
char** param = argv;
int a, b, res;
param++;
//error case
if(argc != 4 && argc != 5) {
//not a valid input
printf("Not a valid input");
return -1;
}
if(argc == 5) {
numSys = param[0][0];
param++;
}
op = param[1][0];
switch(numSys) {
case 'b':
a = ConvCharToBin(param[0]);
b = ConvCharToBin(param[2]);
break;
case 'd':
sscanf(param[0], "%d", &a);
sscanf(param[2], "%d", &b);
break;
case 'h':
sscanf(param[0], "%x", &a);
sscanf(param[2], "%x", &b);
break;
case 'o':
sscanf(param[0], "%o", &a);
sscanf(param[2], "%o", &b);
break;
default:
//no viable number system
return -1;
}
switch(op) {
case '+':
res = a + b;
break;
case '-':
res = a - b;
break;
case '/':
res = a / b;
break;
case '*':
res = a * b;
break;
case '&':
res = a & b;
break;
case '|':
res = a | b;
break;
default:
//no valid operand
printf("invalid operation\n");
return -1;
}
stack_t tmp;
tmp.size = 0;
int i;
switch(numSys) {
case 'b':
while (res) {
if (res & 1) {
tmp.data[tmp.size] = '1';
tmp.size++;
} else {
tmp.data[tmp.size] = '0';
tmp.size++;
}
res >>= 1;
}
for(i = tmp.size - 1; i >= 0; i--) {
printf("%c", tmp.data[i]);
}
printf("\n");
break;
case 'd':
printf("%d\n", res);
break;
case 'h':
printf("%x\n", res);
break;
case 'o':
printf("%o\n", res);
break;
}
return 0;
}
int ConvCharToBin(char* input) {
char* idx;
int res = 0x00000000;
for(idx = input; idx < input + strlen(input); idx++) {
res <<= 1;
if(*idx == '1') {
res |= 0x00000001;
}
}
return res;
}
The sscanf reads formatted data from a string (in you case the argv strings)
This can be parsed using the following:
%d for decimal;
%x for hexadecimal;
%o for octal.
Unfortunately there is no C standard for parsing binary using sscanf, so this is done apart using the stdout.
I would also point out that this implementation has two limitation
Input/output limited to 32 bit unsigned (so from 0 to 4294967295), but with some slight modifications it can be extended;
No error checking for the input values, this can also be easily implemented.
[UPDATE]: The answer by Keine Lust, to explicitly declare the size of array solves the problem.
I am trying to write my own decimal to binary converter in C (posted below), which constantly is giving wrong outputs due to alteration of value of variable named a. Why is the alteration happening? And the compiler I'm using is gcc.
#include <stdio.h>
#include <string.h>
#include <math.h>
int main(void) {
int j = 0; // This variable is used to counter the iterations of while-loop
int a; // This variable holds user-input
char b[] = {}; // This is character array to hold the value of bits after operation
printf("Enter a number to convert into binary\n>>>");
scanf("%d", &a);
while(a!=0){ // Loop until the value of a is 0
printf("a before modulus: %d \n", a); // printing a for debugging
int bit = a % 2; // represents binary digit
printf("a after modulus:%d \n", a); // print a for debugging
switch(bit){ // switch-case to identify the bit
case 1:
b[j] = '1';
break;
case 0:
b[j] = '0';
break;
}
printf("a after switch-case:%d \n", a); // the value of a is altered after switch-case, check output.
a = (int) floor((float)(a/2));
j += 1;
}
printf("\n");
return 0;
}
OUTPUT: (input: 2)
a before modulus:2
a after modulus:2
a after switch-case:48
a before modulus: 24
a after modulus:24
a after switch-case:12312
a before modulus: 6156
a after modulus:6156
..... continues
COMPLETED CODE THAT WORKS: [UPDATE]
#include <stdio.h>
#include <string.h>
#include <math.h>
int main(void) {
const int MAX_SIZE = sizeof(char) * 10000; // Will hold 10000 characters
int j = 0; // This variable is used to counter the iterations of while-loop
int a,temp; // This variable holds user-input
char b[MAX_SIZE]; // This is character array to hold the value of bits after operation will hol
printf("Enter a number to convert into binary\n>>>");
scanf("%d", &a);
temp = a;
int bits = log(a)/log(2);
bits += 1;
while(a!=0){ // Loop until the value of a is 0
int bit = a % 2; // represents binary digit
switch(bit){ // switch-case to identify the bit
case 1:
b[j] = '1';
break;
case 0:
b[j] = '0';
break;
}
a = a/2;
j += 1;
}
printf("The %d in binary is: ",temp);
for (int c=(bits-1);c>=0;c--) {
printf("%c", b[c]);
}
printf("\n");
return 0;
}
This question already has answers here:
How can I correctly assign a new string value?
(4 answers)
How do I properly compare strings in C?
(10 answers)
Closed 5 years ago.
I'm writing a program to play battleship.
I have a string matrix representing the battlefield.
#define NUM_CASELLE 6
char* campo[NUM_CASELLE][NUM_CASELLE];
At the beginning of the program each element of the matrix is initialized with "-".
I noticed that I have problems accessing the matrix elements so I did some debugging to better understand what the problem was and I noticed this: if I write
printf("The content is %s\n", campo[3][1]);
the result is
The content is -
and that's right.
But if I enter coordinates from stdin and memorize them in variables,
printf("row is %c\n", row);
printf("col is %d\n", col);
printf("The content is %s\n", campo[row][col]);
the result is as follows:
The content is (null)
Where am I wrong?
Anyway, I post the whole code because maybe the error is elsewhere.
In fact, the coordinates are entered as they are in battleship, for example, a3 or b5 or f1 etc .. and then I convert the letter to the respective row index.
#define NUM_CASELLE 6
#define NUM_NAVI 7
int pos_size = 256;
char* campo[NUM_CASELLE][NUM_CASELLE];
void posizionaNavi(){
char pos[pos_size];
int i = 0;
int col;
int row;
printf("Scegli dove posizionare le navi...\n");
while(i < NUM_NAVI){
printf("Posizionare nave numero %d...\n", i + 1);
fgets(pos, pos_size, stdin);
col = isCommandValid(pos);
row = pos[1];
if(col == -1){
printf("\n");
printf(">> ATTENZIONE: formato errato.\n");
printf(">> Le colonne vanno dalla lettera A alla lettera F\n");
printf(">> Le righe vanno dal numero 1 al numero 6\n");
printf(">> Esempi di comando valido: a3 - b6 - f1\n");
printf("\n");
}
else{
printf("row is %c\n", row);
printf("col is %d\n", col);
printf("The content is %s\n", campo[row][col]);
printf("The content is %s\n", campo[3][1]);
if(campo[row][col] = " - "){
campo[row][col] = " x ";
printf("Nave %d posizionata in %s\n", i + 1, pos);
i++;
}
else{
printf(">> ATTENZIONE: casella giĆ occupata da una nave.");
printf(">> Riprovare...\n");
printf("\n");
}
}
}
}
int isCommandValid(char* pos){
int ret;
if(strlen(pos) != 3 || pos[1] > '6' || pos[1] < '1')
return -1;
switch(pos[0]){
case 'a':
ret = 1;
break;
case 'A':
ret = 1;
break;
case 'b':
ret = 2;
break;
case 'B':
ret = 2;
break;
case 'c':
ret = 3;
break;
case 'C':
ret = 3;
break;
case 'd':
ret = 4;
break;
case 'D':
ret = 4;
break;
case 'e':
ret = 5;
break;
case 'E':
ret = 5;
break;
case 'f':
ret = 6;
break;
case 'F':
ret = 6;
break;
default:
ret = -1;
break;
}
return ret;
}
1.
case 'f':
ret = 6;
break;
case 'F':
ret = 6;
break;
easier
case 'F':
case 'f':
ret = 6;
break;
2.
Cannot compare string's with ==.
You have to use strcmp().
strcmp(campo[row][col], "-")
3.
You should write program's in american english, especially if you are pasting them somewhere.
4.
Dont forget to check return value's.
5.
char* campo[NUM_CASELLE][NUM_CASELLE];
is pointer to double array, change it to
char campo[NUM_CASELLE][NUM_CASELLE];
so you can do campo[x][x] now.
6.
row = pos[1];
Here you are assigning ascii value of character, do
row = pos[1] - '0';
if(campo[row][col] = " - "){ is an assignment and then a test, not a string nor pointer compare #barmar.
Likely code should use strcmp() to compare strings.
if(strcmp(campo[row][col], " - ") == 0) {
OP says "matrix is initialized with "-"." This differs from the above compare target.
// This is not initialization, only a defintion without initialization
char* campo[NUM_CASELLE][NUM_CASELLE];
...
// potential unposted "initialization" code, needed for each campo[row][col]
campo[row][col] = "-"; // this will not compare as above
campo[row][col] = " - "; // this will compare as above
I suspect unposted code has trouble with campo[row][col] and other issues.
Yes. It is correct. Your table is two dimensional array of pointers. And it can't store anything else but the pointers.
The cell can point to something valid if you:
Allocate the memory and then store something in that allocated memory
campo[x][y] = malloc(size);
strcpy(campo[x][y], "Hello.");
Assign the cell with the valid pointer
char str[] = "hello";
char *str1 = "HELLO";
campo[x][y] = str;
campo[n][n] = str1;
campo[a][b] = "Hello Again";
If you have already assigned the pointer with the address of the valid string, there is nothing in like string comparition operator
if(campo[row][col] = " - ") - will assign campo[row][col] with the address of the string literal " - " and if will consider it as the truth as the valid pointer always cast to non zero integer (but you get the warning)
if(campo[row][col] == " - ") will compare the pointer campo[row][col] with the address of string literal " - "
if(!strcmp(campo[row][col] , " - ")) will check if both string are equal
I was wondering how to reverse my output to match entered number.
Example if user entered 543210, I want the output to be: Five Four Three Two One Zero. But instead it's reversed and I can't figure out how to reverse it.
I can't use loops or anything else.
Code:
int main(void){
int value;
int digit;
printf("enter:");
scanf("%i", &value);
while(value)
{
digit = value % 10;
value = value / 10;
if(digit != 0)
{
switch(digit)
{
case 0:
printf("zero ");
break;
case 1:
printf("one ");
break;
case 2:
printf("two ");
break;
case 3:
printf("three ");
break;
case 4:
printf("four ");
break;
case 5:
printf("five ");
break;
case 6:
printf("six ");
break;
case 7:
printf("seven ");
break;
case 8:
printf("eight ");
break;
case 9:
printf("nine ");
break;
}
}
}
return 0;
}
Exmaple: If user entered 1234
Output would be: four three two one.
How would I fix it to be: One Two Three Four.
Since you've said that you aren't allowed to use loops, then recursion really is the thing that you are probably being expected to use. I personally am not sure if it would be right to not consider a recursion as a loop, but whatever.
You are using a while there, which also is a loop. If you are allowed to use loops, then you could just do the following, easy-to-understand modification in your code, and get the output you desire:
...
int input; // <-- added this
int value;
int digit;
printf( "enter:" );
scanf( "%i", &input ); // <-- notice the change in variable usage
value = 0;
while ( input ) {
value = 10 * value + input % 10; // adds the last digit of input to value from right
input /= 10;
}
while ( value ) { ... }
...
If you aren't allowed to use loops, then you probably are expected to use a special function, a function which outputs a specific value for a single case, and returns back to itself in any other case. You need a recursive function. Examine this simple example:
// This is in maths, not C
f(x) = 2x + 1 for all integer x >= 0
Out of many ways, this one way to describe the function which maps 0 to 1, then 1 to 3, then n to 2n + 1. If we wanted to define the exact same function recursively:
// In maths
f(x = 0) = 1 for x = 0
f(x > 0) = f(x-1) + 2 for integer x > 0
You see what's going on in there? It's saying that each subsequent f(x) is 2 greater than the previous one f(x-1). But more importantly, the function is calling itself! If you look closer, the called function f(x-1) will also call itself:
f(x) = f(x-1) + 2
f(x) = f(x-2) + 2 + 2
f(x) = f(x-3) + 2 + 2 + 2
...
// all these are the same
All this calling deeper and deeper has to end somewhere, and that somewhere is when f(x-...) is f(0), which has been explicitly defined to be 1.
This is what recursion is all about. Let me write out the examples I gave above in C:
// non-recursive version
int fnonrec( int x ){
return 2 * x + 1;
}
// recursive version
int frec( int x ){
if ( x == 0 )
return 1; // explicit return value for f(0)
else // redundant else, hehe
return frec( x - 1 ) + 2;
}
Definitions of the functions really look similar to how they were defined in maths, don't they? Yeah, well, I don't think giving you the answer for your question would be nice of me. All I can say is that you can print things in reverse really nicely with recursive functions.
//store user input to int variable "value"
char str[15];
sprintf(str, "%d", value);
You can then use the strrev function to reverse the string array. Manipulate it from there.
#include <stdio.h>
void print(int v){
static char *numbers[] = {
"zero","one","two","three","four",
"five","six","seven","eight","nine"
};
int digit = v % 10;
int value = v / 10;
if(value){
print(value);
printf(" %s", numbers[digit]);
} else
printf("%s", numbers[digit]);
}
int main(void){
int value;
printf("enter:");
scanf("%i", &value);
print(value);
return 0;
}
Example using recursive function and numbers from the parameters :
#include <stdio.h>
void display(char c)
{
char *numbers[] = {
"zero","one","two","three","four",
"five","six","seven","eight","nine "
};
printf("%s ", numbers[c]);
}
int aff_num(char *c)
{
if (*c == '\0')
return (0);
display(*c-48);
aff_num(++c);
return (1);
}
int main(int argc, char **argv)
{
if (argc < 2)
{
printf("Need numbers\n");
return (-1);
}
aff_num(argv[1]);
return (0);
}
I'm a python hacker and I almost never program in C. that being said:
#include <stdlib.h>
#include <stdio.h>
int highest_power_of_ten(int value){
int exponent = 0;
int tens = 1;
while(value > tens){
tens *= 10;
exponent += 1;
}
return exponent-1;
}
int pow(int base, int exponent){
if (exponent == 0)
return 1;
int temp = base;
while(exponent > 1){
base *= temp;
exponent -= 1;
}
return base;
}
int main(int argc, char** argv){
char* digits[] =
{"zero","one","two","three","four","five","six","seven","eight","nine"};
int value, n, exp, x;
scanf("%i", &value);
while(highest_power_of_ten(value)>0){
exp = highest_power_of_ten(value);
x = pow(10, exp);
n = value/x;
printf("%s ",digits[n]);
value -= n*x;
}
printf("%s\n", digits[value]);
//system("PAUSE"); for windows i guess
return 0;
}
Another method to get the digits in the right order:
E.g. To get the digit at 1st position in 123 divide 123 by 100, to get 2nd - 123 / 10, to get 3rd 123 / 1. That equals: value / 10^(index of desired digit)
So what we have to do is
Get the length of the (remaining) number by calculating log10(value).
Then get the (remaining) first (most significant) digit by dividing value by 10^length (length of 1.)
calculate value := value - 10^length and start from 1, unless the result is 0 (mind handeling numbers that end on 0).
while (value)
{
len = log10(value);
digit = (int) value / pow(10, len);
value -= pow(10, len);
}
And your code does never enter case 0. To fix that just leave the if(digit != 0) - that's what I meant when I wrote "mind the 0").
if(digit != 0) // enters if digit is not 0
{
switch(digit)
{
case 0: // enters if digit is 0
...
}
}
I'm trying to get ints from a c file that has input like this:
(0 3 200 3) (0 9 500 3) (98 20 500 3) (100 1 100 3) (100 100 500 3)
atoi and s work fine for the first number after the parenthesis (I use a while loop and strcat numbers larger than one digit) and any number that is only one digit, but they only return the first digit for numbers that are not right after the parenthesis.
Here is what the code for the method:
void allProcesses(FILE file, struct process processArray[]) {
char ch;
int number;
int a, b, c, io;
int arrayCount = 0;
int processIndex = 0;
char temp[1];
while ((ch = fgetc(&file)) != EOF) {
if (isdigit(ch)) {
char numberAppended[20] = "";
while (isdigit(ch)) {
temp[0] = ch;
strcat(numberAppended, temp);
ch = fgetc(&file);
}
char* end;
number = (int)strtol(numberAppended, &end, 0);
printf("The number is %d\n",number);
int atoinum = atoi(numberAppended);
switch (processIndex) {
case 0:
a = number;
if (DEBUG == TRUE) {
printf("a = %c\n", a);
printf("NUmber a is %d\n", a);
}
processIndex++;
break;
case 1:
b = number;
if (DEBUG == TRUE) {
printf("b = %c\n", b);
printf("NUmber b is %d\n", b);
}
processIndex++;
break;
case 2:
c = number;
if (DEBUG == TRUE) {
printf("c = %c\n", c);
printf("NUmber c is %d\n", c);
}
processIndex++;
break;
case 3:
io = number;
if (DEBUG == TRUE) {
printf("io = %c\n", io);
printf("NUmber io is %d\n", io);
}
processIndex++;
break;
default:
break;
}
}
if (ch == ')') {
processArray[arrayCount] = makeProcess(a, b, c, io);
arrayCount++;
processIndex = 0;
}
}
}
First (read comments):
you have declared char temp[1]; one size it has to be of size 2 according to your code(otherwise undefined behavior because memory overrun):
char temp[2];
while (isdigit(ch)) { // from `(` to `)`
temp[0] = ch; // should be a null terminated
temp[1] = '\0'; // add this step;
strcat(numberAppended, temp);
ch = fgetc(&file);
}
Second: your numberAppended is parse to a string of kind: "0 9 500 3"
and your are calling
number = (int)strtol(numberAppended, &end, 0);
^
output argument
syntax for strtol:
long int strtol(const char *numberAppended, char **end, int base);
Where
numberAppended: is the string to be converted into a long integer.
end: points to a pointer that will be set to the character immediately following the long integer in the string "numberAppended".
And your are to write something like this: (read comments)
end = numberAppended; // assign to first string
// in a loop {
number = (int)strtol(end, &end, 0); // in loop end is input &end is output
printf("The number is %d\n",number);
//}
My following code will help your to understand how to use strtol() to parse and extract number from numberAppended string:
#include <stdio.h> /* printf */
#include <stdlib.h> /* strtol */
int main (){
char numberAppended[] = "2001 11 223 444 566";
char * end;
long int li;
end =numberAppended;
int base =10;
int ele = 0;
while(li=strtol (end, &end, base)){
printf("%ld \n", li);
ele += 1;
}
printf("\nNo of elements: %d", ele);
return 0;
}
output:
2001
11
223
444
566
No of elements: 5
third: may be its not an error but I couldn't find where processIndex updates in your code before switch(){}..