Extract an integer value from array and program without showing printf function - c

I want to extract a number from an array I introduce in the keyboard and convert it into one integer. My code is:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
int r, t, i;
char expressio[t];
char vector[50];
char rpn[t][4];
printf("Introduce the expresssion");
fgets(expressio, t, stdin);
t = strlen(expressio);
for (i = 0; i <= t; i++) {
if (isdigit(expressio[i])) {
r = atoi(expressio[i]);
vector[i] = rpn[0][r];
}
return 0;
}
}
I have this warning:
passing argument 1 of 'atoi' makes pointer from integer without a cast
How can i solve it?
Also, when I execute this program, it does nothing and it doesn't even print the "Introduce the expression". Why is this happening?

That warning means that you are passing a bad argument to the function. "atoi" is expecting an array of chars as argument, but you are passing a single char as argument here:
r = atoi(expressio[i]);
If you want to convert a single char into a number, you can do:
r = expressio[i] - '0';
If you look at the ascii table, you will notice that the ascii value of 0 is 48. If you substract 48 (or, like i did, the ascii value of 0) to your char expressio[i], you will get the corresponding number as an integer. Like this, if expressio[i] equals '8', then r will equal 8.

Related

How do I subtract 1 from an array of integers

I am learning C in school, and I am having a little difficulty on my project.
Basically, I am writing a function that gets a string containing a positive integer. The function subtracts 1 from that integer and puts the obtained value in the string.
So , if I have this ;
char nums[] = "2462";
how do I write a function that will subtract 1 from the integer, so that the result is "2461"??
First, convert the character array into an integer.
You can use atoi (ASCII to Integer), but because it returns 0 on error there's no way to tell the difference between successfully converting "0" and an error.
Instead use strtol (STRing TO Long integer).
// end stores where parsing stopped.
char *end;
// Convert nums as a base 10 integer.
// Store where the parsing stopped in end.
long as_long = strtol(nums, &end, 10);
// If parsing failed, end will point to the start of the string.
if (nums == end) {
perror("Parsing nums failed");
}
Now you can subtract, turn the integer back into a string with sprintf, and put it in nums.
sprintf(nums, "%ld", as_long - 1);
This is not entirely safe. Consider if nums is "0". It only has 1 byte of space. If we subtract 1 then we have "-1" and we're storing 2 characters where we only have memory for 1.
For the full explanation of how to do this safely, see How to convert an int to string in C?.
Alternatively, don't store it, just print it.
printf("%ld", as_long - 1);
One way is to convert string -> int -> string.
You can do this by using atoi and sprintf.
Simple implementation (far from perfect):
#include <stdlib.h>
#include <stdio.h>
int main()
{
int a;
char b[5];
a = atoi("2462");
a--;
sprintf(b, "%d", a);
printf("%s\n", b);
return 1;
}

Using atoi, grabbing integer from string

#include<stdio.h>
#include<conio.h>
#include<string.h>
int main() { {
char sir[3000];
int i;
int suma = 0;
int lungime;
scanf("%s", sir);
lungime = strlen(sir);
char x;
char *pX;
x = sir[2];
pX = &x;
suma = atoi(pX);
return 0;
}
I am doing the adventOfCode, Day1.
My problem is that I cannot pick certain digits from the string, using atoi.
From what I read, atoi needs a pointer as argument.
if i read some big string like "111555434536563673673567367...."
with a length between 2000 - 3000
I can't understand why when I print "suma", instead of printing the certain digit from my string, it prints some huge integer, like 83506.
From what I read, atoi needs a pointer as argument.
Needing a pointer is only part of the deal. The other part is that the pointer needs to point to a null-terminated string representing an integer.
Moreover, x = sir[2]; pX = &x is not how you get a pointer to the second element of sir[] array: x is a copy of the third digit (arrays are zero-based), and pX is a pointer to that copy.
If you want to get a numeric value of a single digit, subtract '0' from it (note single quotes around zero):
int thirdDigitVal = sir[2] - '0';
If you need to do it with atoi, copy the digit into a null-terminated string:
char copy[2] = {0};
copy[0] = sir[2];
int thirdDigitVal = atoi(copy);

compare two numbers in c using char and strcmp

I am trying to compare two set of data using strcmp. This first set of data are var1 which is get from fgets(var1, 100, stdin). The second set of data are generate randomly by rand. When I complie it, I get two same errors. They both come from char f.
warning: assignment makes pointer from integer without a cast printf(f);
warning:assignment makes pointer from integer without a cast if (strcmp(var1,f)==0)
i already declare the randomly generated number char f = rand() % 38; in char, why will it not work?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
int main()
{
char var1[100];
int result;
fgets(var1, 100, stdin);
srand(time(NULL));
char myArray[38] = { 1,5,3,4};
char f = rand() % 38;
printf(var1);
printf(f);
if (strcmp(var1,f)==0) {
result = 1;
printf("It work\n");
}
else {
printf("It didn't work!\n");
result = 0;
}
return 0;
}
EDITED CODE
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
int main()
{
char var1[100];
int result;
scanf("%s",var1);
srand(time(NULL));
char myArray[7] = { 0,28,9,26,30,11,7 };
int randomindex= 1 + (rand() % 100);
char f = myArray[randomindex];
char str_f[2] = { f, '\0' };
printf("var1: %s\n",var1);
printf("%s",str_f);
printf("\n");
if (strcmp(var1,str_f)==0) {
result = 1;
printf("It work\n");
}
else {
printf("It didn't work!\n");
result = 0;
}
return 0;
}
As commented above, in C Langage, functions from Library have a strict format and using not that expected format will occur warning or error at compilation time or runtime.
Function 1 - the printf() is the common function to write C strings to the standard output stdout (declared in <stdio.h>).
See the C library function - printf()
int printf(const char *format, ...)
In the provided source code, the printf() function has been used in the following cases:
printf("It work\n"); to write a fixed string which complies with the const char * expected format of the first parameter ==> OK,
printf(var1); to write the content of the entered string var1 (declared as char var1[100];) which not exactly complies with const char * of the first parameter but will be cast during compile time. A proposed format to write the var1 string could be printf("%s",var1); (or more verbose printf("var1: %s",var1);) where the first parameter "%s" will specify that the following argument var1 will be a string.
printf(f); to write the content of the random value (declared as char f;) which doesn't comply with const char * of the first parameter and doesn't compile at all. The minimal expected format to write the f character is printf("%c",f); (or more verbose printf("f=%c",f);) where the first parameter "%c" will specify that the following argument f will be a character.
Function 2 - the strcmp() is a function to compare two C strings parameters (declared in <string.h>.
See the C library function - strcmp()
int strcmp(const char *str1, const char *str2)
In the provided source code, the strcmp() function has not been used as specified. The function expects two input parameters:
First parameter of strcmp(var1,...)==0 is var1 (declared as char var1[100];) which not exactly complies with const char * but will be cast during compile time.
Second parameter of strcmp(...,f)==0 is f (declared as char f;) which doesn't comply with const char * and doesn't compile at all.
To compare the character f with var1, it shall be necessary to
convert it to a string (In C, a string is an array of char ended by
a character).
Solution 1 - how to convert the character char f; to a string.
A C string is an array of characters: char str_f[]= { '<char>', ... , '<NUL>' };. Meaning that a minimal array of 2 characters is necessary to convert the character char f; to a string.
char f = rand() % 38;
// use a 2 characters string
char str_f[2] = { f, '\0' };
// Could be also initialised as str_f[0] = f; str_f[1] = '\0';
// compare the strings using `str_f`
if (strcmp(var1,str_f)==0) {
Warning 1 - be careful to the random value range.
When printing characters, a C string is supposed to be filled by ASCII
characters different from which is used to end the string.
In the provided source code, the assignment of f, char f = rand() % 38;, will generate values from 0 to 37 which include the character and the first 31 non-printable characters (ctrl-characters). Only characters greater than 31 will be displayed.
In will be more easy to generate: char f = ' ' + (rand() % 38);
where ' ' is the first printable ASCII character = 32.

Subscripted value nor array nor pointer nor vector

This is my program to convert a binary to a decimal value.
#include <stdio.h>
#include <string.h>
#include <math.h>
void con(){
unsigned long long int dec = 0, bin;
int i;
printf ("\n Binary : ");
scanf("%lld",&bin);
for (i = strlen(bin) - 1; i <= 0; --i){ // Warning in here
dec = dec + (bin[i] * pow (2, i)); // Error in here
}
printf(" Decimal : %lld",dec);
con();
}
int main(){
con();
return 0;
}
When i compile the code, this error shows up ," Subscripted value is neither array nor pointer nor vector". And this warning also ," Passing argument 1 of strlen makes pointer from integer without a cast".
Why am i getting these and how can i fix them?
There are a number of problems with your code.
Most important is the variable bin. You probably want it to be a string like "1001001001" but you define it as unsigned long long int. Instead you should do:
char bin[100];
scanf("%s", bin); // Note: Not recommended! Use fgets instead.
Here scanf is not recommended as the user may overflow your buffer. Please use fgets instead.
As suggested by #MayurK: If you want to use scanf then at least do:
scanf("%99s", bin);
to prevent buffer from overflow.
Then this part:
dec = dec + (bin[i] * pow (2, i));
is wrong as bin[i] is not a number but a char.
You could do:
dec = 2 * dec + (bin[i] - '0'); // Note: No error checks which is bad
It will work as long as the user only inputs 0 and 1. In real code you should check that the user actually did so.
Finally you should not call con at the end of the function as it will give an endless loop. So delete that call:
printf(" Decimal : %lld",dec);
// DELETE THIS con();
}
dec = dec + (bin[i] * pow (2, i)); //bin is a numeric type
In this line you are trying to use a variable of unsigned long long type as array. Every numeric type is taken as a full value, you can't use array indexing to access separate digits. If you want to use it as a array use a char* or character array.
And you are also passing a unsigned long long to strlen(const char * str) function.

How to convert each character in a character array to integer?

I have tried the standard methods but still I get error in my answer.
My code:
int main() {
int val;
char str[] = {'1', '45', '0'};
val = str[1] - '0';
printf("Int value = %d\n", val);
return(0);
}
I am getting answer as 5 instead of 45.
How do I solve this issue?
[update from comment:]
I actually need to process an array of strings..suppose I want to convert octal numbers to decimal, and my input has to be in the form of an array of strings. I wish to convert these no.s to decimal : {45,17,100} For that I would, at first be requiring to extract each element and change it to integer. Could you plz suggest what would be the best way to do it?
I actually need to process an array of strings
What you have defined here
char str[] = {'1', '45', '0'};
is not an array of strings, but exactly one array of char with 3 elements. It is not even a C-"string", as this would require a trailing value of 0. Note that the value of the character '0' isn't 0, but, for example, for the ASCII character set it's 48.
'45' is a multi-byte character literal, which in fact is an integer. The code above tries to initialise the 2nd element of the char-array str (str[1], which is a char) using this very literal.
This does not work.
A char cannot (necessarily) hold the int value of this multi-byte character literal. In this case the initialisation of str[1] overflows, resulting in the unexpected value of 5.
To see the issue try the following code:
#include <limits.h>
#include <stdio.h>
int main(void)
{
char c_min = CHAR_MIN;
char c_max = CHAR_MAX;
unsigned char uc = '45';
printf("'1'=%d\n", '1');
printf("'45'=%d\n", '45');
printf("'0'=%d\n", '0');
printf("lowest possible value for char=%d\n", c_min);
printf("highest possible value for char=%d\n", c_max);
printf("'45' converted to an (unsigned) char=%u\n", uc);
return 0;
}
The example above shows how the value of 45 gets truncated when being assigned to char.
Depending on the C implementation you use the conversion of '45' to a char might even invoke the infamous Undefined Behaviour. This is not good.
What you seem to be wanting is:
#define ARRAY_SIZE_MAX 3
char * str[ARRAY_SIZE_MAX] = {"1", "45", "0"}; /*. Mind the double quotes. */
This defines an array of 3 pointers to char , with each pointing to a C-"string".
Here, you are getting 5 instead of 45 because st[1] = '5', this is because we have only ASCII value of 0 to 9 integers and 45 have no ASCII value.
To store 45 in your string you have to declare multidimensional string.
for example:
char st[3][3]={'1', '45', '0'};
Here is the working code:
#include<stdio.h>
int main(){
int i,ans,j;
char st[3][3]={{'1'}, {'4','5'},{'0'}};
for(j=0;j<3;j++){
for(i=0;st[j][i]>=48 && st[j][i]<=57;i++){
ans=st[j][i]-'0';
printf("%d",ans);
}
printf("\n");
}
return 0;
}
Output is
1
45
0
It depends, what do you want.
Every character has it's own int value- It's simply ASCII code
If you will iterate over integers and make it print like %c you will get ASCII table (you can see it eg. there.
But if you want to read int values from string / char datatype you will have to parse it- atoi (ascii to integer) function- example there
Btw I dont know how exactly your example works but the problem is you are doing following: int val = '45' - '0'; int value of '0' should be 48, '45' rly I dont know, but '4' is 52int and '5' is 53 int, so something like that..
As i wrote you should to do something like int val = atoi('45') - atoi('0') just for sure maybe better to cast into int as follows int val = (int) (atoi('45') - atoi('0')) - exactly asi in your example
int main() {
int val;
char str[] = {'1', '45', '0'};
val = (int) (atoi(str[1]) - atoi('0'));
printf("Int value = %d\n", val);
return(0);
}
Not sure, but i think that should works, hope that will help

Resources