convert char array to integer value and add them - c

How can I extract numbers from a char array, separated with spaces, convert them to integers and sum them? For example:
"34 54 3 23"

I'd start at the beginning of the array, check each character in turn with isdigit() and keep a current value and a current total.
When reaching the terminating NUL char (or last element of the array), the current total is already calculated.

You need to parse the string.
If you know how many integers are in there, you could use just a sscanf.
Otherwise find out where blanks are (with something similar to strtok, for example) and then read integers using atoi

Related

How to get specific adjacent characters of a string and add it to an another string in C

I have an abstract concept to use a for-loop to get specific adjacent characters of a string and add it to a stack, basically take all the constants of a string expression and add it to the stack separately; For example string: "1111+(2222-3333)" would be put in to the stack like "1111","2222", and "3333". I have a code below to start with that abstract concept but first trying it out with a simple one, and unfortunately it doesn't output the desired result of copying the specific adjacent characters.
char expression[20]={""},sub[20]={""};
scanf("%[^\n]%*c",&expression);
sub[15]=expression[15];
sub[16]=expression[16];
sub[17]=expression[17];
sub[18]=expression[18];
printf("%c %c %c %c\n",sub[15],sub[16],sub[17],sub[18]); //to check if copied successfully
printf("sub= %s",sub); //doesnt print expected output
After this declaration
char expression[20]={""},sub[20]={""};
all elements of the array sub contain zeroes.
You changed elements of the array starting from the position 15
sub[15]=expression[15];
sub[16]=expression[16];
sub[17]=expression[17];
sub[18]=expression[18];
The elements before the position still store zeroes.
So this call of printf
printf("sub= %s",sub);
assumes that the array contains an empty string because it first character is the terminating zero character '\0'.
Instead you could write
printf("sub= %s",sub + 15 );
Or you could change the assignments like
sub[0]=expression[15];
sub[1]=expression[16];
sub[2]=expression[17];
sub[3]=expression[18];
and then use
printf("sub= %s",sub);
Pay attention to that the second argument of this call of scanf
scanf("%[^\n]%*c",&expression);
is incorrect. You have to write
scanf("%[^\n]%*c",expression);

Confusion with usage of strcmp() for number strings

{
char array[2][10]={"3234","5"};
int n=strcmp(array+0,array+1);
printf("%d",n);
}
The following code prints -1, event though 3234>5.
It however prints 1 if the first number is 5234 or 6234 etc.
What is the logic behind the results?(Are only the first digits taken
into account?)
So, is there a way to compare two number strings without comapring
their actual integer values?
What is the logic behind the results?
strcmp compares characters in the strings, using their values as unsigned char. First, it compares the first character of one string with the first character of the other. If they differ, it reports the first string is “lesser than” the second if its character is lesser than the other’s and it reports “greater than” if the first string’s character is greater. If the characters are equal, then strcmp compares the second characters of the strings, then the third, and so on. (If one string is shorter than the other but is identical up to its end, the null character that terminates it will cause it to be lesser than the other string.)
So, is there a way to compare two number strings without comapring their actual integer values?
There is no standard library routine for this. You could write a routine for it.

Last value of char array unknown - C

I'm making a simple program in C, which checks the length of some char array and if it's less than 8, I want to fill a new array with zeroes and add it to the former array. Here comes the problem. I don't know why the last values are some signs(see the photo).
char* hexadecimalno = decToHex(decimal,hexadecimal);
printf("Hexadecimal: %s\n", hexadecimalno);
char zeroes [8 - strlen(hexadecimalno)];
if(strlen(hexadecimalno) < 8){
for(i = 0; i < (8-strlen(hexadecimalno)); i++){
zeroes[i]='0';
}
}
printf("zeroes: %s\n",zeroes);
strcat(zeroes,hexadecimalno);
printf("zeroes: %s\n",zeroes);
result
In C, strings (which are, as you are aware, arrays of characters) do not have any special metadata that tells you their length. Instead, the convention is that the string stops at the first character whose char value is 0. This is called "null-termination". The way your code is initializing zeroes does not put any null character at the end of the array. (Do not confuse the '0' characters you are putting in with NUL characters -- they have char value 48, not 0.)
All of the string manipulation functions assume this convention, so when you call strcat, it is looking for that 0 character to decide the point at which to start adding the hexadecimal values.
C also does not automatically allocate memory for you. It assumes you know exactly what you are doing. So, your code is using a C99 feature to dynamically allocate an array zeroes that has exactly the number of elements as you need '0' characters appended. You aren't allocating an extra byte for a terminating NUL character, and strcat is also going to assume that you have allocated space for the contents of hexadecimalno, which you have not. In C, this does not trigger a bounds check error. It just writes over memory that you shouldn't actually write over. So, you need to be very careful that you do allocate enough memory, and that you only write to memory you have actually allocated.
In this case, you want hexadecimalno to always be 8 digits long, left-padding it with zeroes. That means you need an array with 8 char values, plus one for the NUL terminator. So, zeroes needs to be a char[9].
After your loop that sets zeroes[i] = '0' for the correct number of zeroes, you need to set the next element to char value 0. The fact that you are zero-padding confuses things, but again, remember that '0' and 0 are two different things.
Provided you allocate enough space (at least 9 characters, assuming that hexadecimalno will never be longer than 8 characters), and then that you null terminate the array when putting the zeroes into it for padding, you should get the expected result.

Octal-based number format in C

I'm having problem using int values in C that starts with zero's (like 00111001).
I know that C compiler understand zero's in the beginning of a number as an octal number.
My question is how to disable it? I want to turn an 8 digit int into a char array[8].
e.g. 01010001={'0','1','0','1','0','0','0','1'}
If you're using GCC, you can use binary literals. Set the variable to 0b00111001.
https://gcc.gnu.org/onlinedocs/gcc/Binary-constants.html
Surround your number with quotes:
char array[] = "01010001";
The above will make each digit a character in array that you can read as well as placing a '\0' character at the end so that it can be used as a C string - as per your last sentence. Beware, the length of this string (in memory) will be 9 characters though because of this added NUL character.

splitting string in c

I have a file where each line looks like this:
cc ssssssss,n
where the two first 'c's are individual characters, possibly spaces, then a space after that, then the 's's are a string that is 8 or 9 characters long, then there's a comma and then an integer.
I'm really new to c and I'm trying to figure out how to put this into 4 seperate variables per line (each of the first two characters, the string, and the number)
Any suggestions? I've looked at fscanf and strtok but i'm not sure how to make them work for this.
Thank you.
I'm assuming this is a C question, as the question suggests, not C++ as the tags perhaps suggest.
Read the whole line in.
Use strchr to find the comma.
Do whatever you want with the first two characters.
Switch the comma for a zero, marking the end of a string.
Call strcpy from the fourth character on to extract the sssssss part.
Call atoi on one character past where the comma was to extract the integer.
A string is a sequence of characters that ends at the first '\0'. Keep this in mind. What you have in the file you described isn't a string.
I presume n is an integer that could span multiple decimal places and could be negative. If that's the case, I believe the format string you require is "%2[^ ] %9[^,\n],%d". You'll want to pass fscanf the following expressions:
Your FILE *,
The format string,
An array of 3 chars silently converted to a pointer,
An array of 9 chars silently converted to a pointer,
... and a pointer to int.
Store the return value of fscanf into an int. If fscanf returns negative, you have a problem such as EOF or some other read error. Otherwise, fscanf tells you how many objects it assigned values into. The "success" value you're looking for in this case is 3. Anything else means incorrectly formed input.
I suggest reading the fscanf manual for more information, and/or for clarification.
fscanf function is very powerful and can be used to solve your task:
We need to read two chars - the format is "%c%c".
Then skip a space (just add it to the format string) - "%c%c ".
Then read a string until we hit a comma. Don't forget to specify max string size. So, the format is "%c%c %10[^,]". 10 - max chars to read. [^,] - list of allowed chars. ^, - means all except a comma.
Then skip a comma - "%c%c %10[^,],".
And finally read an integer - "%c%c %10[^,],%d".
The last step is to be sure that all 4 tokens are read - check fscanf return value.
Here is the complete solution:
FILE *f = fopen("input_file", "r");
do
{
char c1 = 0;
char c2 = 0;
char str[11] = {};
int d = 0;
if (4 == fscanf(f, "%c%c %10[^,],%d", &c1, &c2, str, &d))
{
// successfully got 4 values from the file
}
}
while(!feof(f));
fclose(f);

Resources