Simple question, below is my code. The number my compiler returns is 4219296. My question is: why? What is my code doing here?
#include <stdio.h>
char array[];
int main()
{
atoi(array);
printf("%d \n", array);
return 0;
}
The function atoi returns the converted value. This value needs to be stored. Here in the above program you are not storing the returned value. So there is no effect on the array variable.
Printing the array in decimal format gives you the address of the array. The program shall print the same value even without the atoi function. To confirm try this:
//...
printf("%d \n", array);
atoi(array);
printf("%d \n", array);
Output remains same.
Here that is printing the address of the starting position in of your array. If you use
a pointer you will get the value of that.
printf(" %d \n",*array);
Here atoi is doing nothing.
If i'm not wrong, you want to convert a string containg a numberic value into an integer.
In your code, because of char array[]; atoi() will face undefined behaviour. You need to pass some valid address to the API.
Also, instead of using atoi(), use the safer counterpart strtol().
Check the below code.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char ip[ ] = "12345";
char *err;
long int retval;
retval = strtol(ip, &err, 0);
printf("strng format : %s, int format %ld\n", ip, retval);
return 0;
}
O/P
[sourav#broadsword temp]$ ./a.out
string format : 12345, int format 12345
Also, if you change the ip to someting like char ip[ ] = "12A45";, then the o/p will look like
[sourav#broadsword temp]$ ./a.out
string format : 12A45, int format 12
Related
I was asked to write a code that converts an integer and turns it into a hex.
I managed to write the code. However, every time I enter the same number I always get a new hex value, is this normal?
Also, why the values are different from expected? for example, if I enter "1" isn't the hex value supposed to be "01"?
The value that I get is something like "95f9a4".
#include <stdio.h>
#include <string.h>
int main(void)
{
int i;
char str[5] = { "\0" };
printf("Please enter a num:");
scanf_s("%d", &i);
sprintf_s(str, "%x", i);
printf_s("%x", str);
}
You have unnecessary code, which resulted in more places to make a mistake.
After sprintf_s(str, "%x", i), str contains the hex representation of i. Then printf_s("%x", str); prints out the str pointer as a hex number.
The minimal fix is to change the latter line to printf_s("%s", str) to output the content of the string str.
The better way would be to just directly print out the hex value, without going through str at all. Replace both lines with just printf_s("%x", i).
For example, I want to separate the string "0013subdivision" into 0013 (as an integer that can do addition, subtraction, etc. not char) and subdivision (as a char itself) in the given string.
This is my code so far:
#include <stdio.h>
#include <stdlib.h>
char location[10]; /* for the input with number and letter */
char x;
int house[10]; /* for the integer that will be separated from the string */
int main()
{
printf("Input: ");
scanf ("%s", &location[x]);
x=0
for (x=0; location[x]!='\0'; x++ );
return 0;
}
Based on my research, the code atoi is used to convert the converted value back to int (if I'm not mistaken) but I don't know when to place the function.
location is char array, if you are reading as string use only %s with string name only, index not required.
scanf ("%s", &location[x]); --> scanf ("%s", location);
After separating only int from char array you need to store one int value into house.
int house[10] --> int house.
Here is the code for extracting only int from string :
char location[10]; /* for the input with number and letter */
int x;
int house = 0 ; /* for the integer that will be separated from the string */
int main()
{
printf("Input: ");
//scanf ("%s", &location[x]);
scanf ("%s", location);
for (x=0; location[x]!='\0'; x++ ) {
if(location[x]>='0' && location[x]<='9') {
house =(house * 10) + (location[x]-48);
}
}
printf("int part = %d \n",house);
return 0;
}
The main problem in the code is
scanf ("%s", &location[x]);
Where you did not impose any limit on the scanning. An input like 0013subdivision will cause out of bound memory access leading to undefined behavior.
Always limit the input size with the length modifier, like, for an array defined as
char location[10]
use the conversion specification like
scanf ("%9s", location); // (i) one element saved for terminating null
// (ii) the array name decays to the pointer to 1st element
//in case of an argument to a function call.
Then, you don't need an integer array to store the extracted integer. A singular variable would suffice.
However, i'd like to suggest a much robust way:
read the user input using fgets()
then, scan the input using sscanf() and appropriate conversion specifier, like %4d%9s or alike.
The most correct way to do this is to use the strto... family of functions from stdlib.h. For example:
printf("%ld\n", strtol(str, NULL, 10));
The atoi family of functions should never be used for any purpose, since they have broken error handling and can be 100% replaced by the strto... functions.
You could use the scanf family of functions but they are needlessly slow and notoriously dangerous, so I don't really see the point of using them here.
If you are interested in implementing the actual copying manually, for learning purposes, it is fairly trivial:
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
int main (void)
{
const char str[] = "0013subdivision";
char number_part [sizeof(str)];
char letter_part [sizeof(str)];
size_t i;
for(i=0; str[i]!='\0' && isdigit(str[i]); i++) // find where the letters start
{}
memcpy(number_part, &str[0], i); // copy digit part
number_part[i] = '\0'; // append null terminator
memcpy(letter_part, &str[i], sizeof(str)-i); // copy letter part + null term
puts(number_part);
puts(letter_part);
printf("%ld\n", strtol(str, NULL, 10));
}
If the string is a run-time variable, you have to use strlen(str)+1 instead of sizeof().
strtol converts string to number and also gives you back the character it stopped on, i.e. first character after number.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
const char* const input = "0013subdivision";
const char* string;
const long number = strtol(input, &string, 10);
printf("Number: %ld String: '%s'\n", number, string);
// Number: 13 String: 'subdivision'
return 0;
}
https://repl.it/repls/SphericalImpracticalTinamou
I have string like
char str[10] = "0123456789";
I need to convert it into int. I tried it with atoi but this function removes 0. I searched it in google and found the same question here. Many answers have provided solution using strtol but its not working. Following is the code I am using for strtol:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char str[30] = "0123456789 This is test";
char *ptr;
int ret;
ret = strtol(str, &ptr, 10);
printf("The number is %d\n", ret);
printf("String part is %s\n", ptr);
return(0);
}
Output:
The number is 123456789
String part is This is test
What's wrong I am doing in this case. How to convert string to int without removing zero's.
You need to format your output accordingly.
%d just prints the int in decimal using the shortest string representation (no leading zeros)
%8d (for example) will print the int in decimal in a field of size 8 (leading spaces if needed)
%08d (for example) will print the int in decimal in a field of size 8 with leading zeros.
I wrote a program to fetch all the phone numbers from a file which has other text like at commands and other error from other child process. Here when I try to convert the string to integer using a user-defined function I facing the problem. The converted value stored in the function is not properly returned to main program, instead its returning some unusual and it seems to be the same for every execution. Its surprising me. Can someone advice me.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char lic[128];
unsigned long long sum=0ULL;
unsigned long long stringtoint(char str[])
{
int i=0;
sum=0;
if(str[strlen(str)]!='\0')
return -1;
//puts("Im in function");
while(str[i]!='\0'){
//printf("- %c -\n",str[i]);
if(str[i] >= 48 && str[i] <= 57){
sum = sum*10 + (str[i] - 48);
//printf("%c and %llu\n",str[i],sum);
}
i++;
}
if(sum>0)
printf("\nIn function passed string is %s and integer value is %llu\n",str,sum);
return sum;
}
FILE *file;
int main(){
//long long int inte;
int64_t inte; file = fopen("receive","r");
if(file!=NULL)
while(fscanf(file,"%s",lic)!=EOF){
inte = 0;
inte=stringtoint(lic);
if(inte !=0){
printf("In Main %llu is the value of the string %s",inte,lic);
if(inte==sum)
printf("\n%llu and %llu are same\n",inte,sum);
}
}
printf("\n");
fclose(file);
return 0;
}
The result I was getting for this program was given below.
In function passed string is 8939095683 and integer value is 8939095683
In Main 349161091 is the value of the string 8939095683
shameerariff#shameerariff-Satellite-L450:~/Workinffolder/ivr/IVRReporting$ ./datadecoder
In function passed string is 8939095683 and integer value is 8939095683
In Main 349161091 is the value of the string 8939095683
shameerariff#shameerariff-Satellite-L450:~/Workinffolder/ivr/IVRReporting$ ./datadecoder
In function passed string is 8939095683 and integer value is 8939095683
In Main 349161091 is the value of the string 8939095683
Your valuable advice are needed, Thank you in advance for your support.
Point 1. You need to change
int stringtoint(char str[])
to
unsigned long long stringtoint(char str[])
Point 2. %lld is not the correct format specifier for unsigned long long. Use %llu
Can someone advice me.
Yes. Don't write your own function, but use the atoi function available in the C standard library if you really want to operate on char arrays, or use the stoi function to work on std::string, or use any C++ iostream to read ints from your strings. With the latter, you can basically just use the file stream you can directly get when opening a ifstream with C++'s standard library.
EDIT: I should mention you shouldn't use atoi/stoi, but atoll/stroul to actually reflect the fact that your numbers could be bigger than whatint can hold.
Also, phone numbers are not integers. In many countries, city area codes start with 0, which you can't represent in any numeric type. In fact, telephone numbers are not numbers, but sequences of digits, if you ask me.
I'm trying to learn some of the basics of C and I have been reading nonstop about gets/fgets/puts/scanf and can't seem to get this right...
My code is:
#include <string.h>
#include <stdio.h>
#define BUFF 256
void main()
{
char s[BUFF];
fgets(s, BUFF, stdin);
s[strlen(s)-1]='\0';
printf("%x %s %d", s, s, strlen(s));
}
I'm trying to get the hex format of the variable s to print, my input is AAAA and the output I want is 41414141 AAAA 4, the output I'm getting is 12fe80 AAAA 4.
I thought I needed to cast s (as a u int) for the hex interpretation, but that didn't work either.
I would really appreciate an explanation on this as well as help, I'm really trying to learn this.
Thank you!
void main()
This isn't your problem, but the correct definition is
int main(void)
void main() is useful mostly as a tool to detect C textbooks written by incompetent authors.
printf("%x %s %d", s, s, strlen(s));
This has undefined behavior:
"%x" requires an argument of type unsigned int; you're giving it a char* (the array expression s is converted to a pointer to its first element).
%d requires an argument of type int; you're giving it a size_t. Either convert it to int, or use %zu.
If you want to print a hexadecimal representation of the contents of the string s, there's no direct way to do that. You'll just have to loop over the characters contained in s and print the value of each one in hexadecimal. (You should cast each char value to unsigned int so it works properly with the "%02x" format.)
%x works on numbers. You're passing in a pointer to a string. So in this case printf() is interpreting the pointer (memory address) as a number and printing that address in hex format. Sounds like you just want to print the ASCII values, in hex, of each character in the input:
for (int i = 0; i < strlen(s); ++i)
printf("%02x", (unsigned) s[i]);
Try this
$ cat hello.c
#include <string.h>
#include <stdio.h>
#define BUFF 256
int main()
{
int i = 0; /* a counter */
char s[BUFF];
fgets(s, BUFF, stdin);
s[strlen(s)-1]='\0';
while (i < strlen(s)) { /* to get the character(s) in s */
printf("%x", s[i]); /* as hex */
i++;
}
printf(" %s %d\n", s, strlen(s)); /* as before */
}
$ gcc hello.c -o hello && echo "AAAA" | ./hello
41414141 AAAA 4
The hex value you are printing is the address of the string, not the contents (since s is a char*).
To see the full contents of the string as hex bytes, you will have to do something like this:
int n = strlen(s);
for(int ii=0; ii<n; ii++) printf("%02x", (unsigned int) s[ii]);
#include <stdio.h>
#include <string.h>
main() {
char a[]="AAAA";
printf("%x%x%x%x %s %d", a[0],a[1],a[2],a[3],a, (int)strlen(a));
}
print all the array index one by one.
printf("%x ", *s);
printf("%x ", *(s+1));
....
....