I am trying to convert an integer(greater than 9 as below 9 it converts easily by the below process) to character. But after conversion I get some characters like '?'..below is the code:
#include <stdio.h>
int main(void) {
int i = 15;
char c;
c=i+'0';
printf("%c", c);
return 0;
}
output: ?
Expected output: 15
"15" are two characters. You would have to convert it digit by digit.
It won't work because you have two digit number. Such simple convertion will work for numbers 0-9 but not for greater. You can use itoa function. Example of use is in the link provided
Making a string from an integer is not possible directly, the reason why this works
int number = 2;
char character = number + '0';
fprintf(stdout, "%c\n", character);
is because '0' is the ascii value that represents the number 0 which is 48, and since they appear in order in the ascii table, adding the number to it will give you the ascii value of the number.
But 15 consists of 2 ascii values, a quick way to perform the conversion is to use an array, like this
char string[3];
int number;
int result;
number = 15;
result = snprintf(string, sizeof(string), "%d", number);
if (result >= sizeof(string))
fprintf(stdout, "the string was truncated, there is no space to store the result");
else if (result < 0)
fprintf(stderr, "an error occurred\n");
else
fprintf(stdout, "%s\n", string);
You have 2 digits which is why printing it out like that doesn't work. If you want to convert the int to a string use sprintf :
int i= 15;
char str[15];
snprintf(str, 15, "%d", i); // str now contains "15"
Related
I'm working on an assignment and as part of it I need to extract the integer from a string.
I've tried using the atoi() function, but it always returns a 0, so then I switched up to strtol(), but it still returns a 0.
The goal is to extract the integers from the string and pass them as arguments to a different function. I'm using a function that then uses these values to update some data (update_stats).
Please keep in mind that I'm fairly new to programming in the C language, but this was my attempt:
void get_number (char str[]) {
char *end;
int num;
num = strtol(str, &end, 10);
update_stats(num);
num = strtol(end, &end, 10);
update_stats(num);
}
The purpose of this is in a string "e5 d8" (for example) I would extract the 5 and the 8 from that string.
The format of the string is always the same.
How can I do this?
strtol doesn't find a number in a string. It converts the number at the beginning of the string. (It does skip whitespace, but nothing else.)
If you need to find where a number starts, you can use something like:
const char* nump = strpbrk(str, "0123456789");
if (nump == NULL) /* No number, handle error*/
(man strpbrk)
If your numbers might be signed, you'll need something a bit more sophisticated. One way is to do the above and then back up one character if the previous character is -. But watch out for the beginning of the string:
if ( nump != str && nump[-1] == '-') --nump;
Just putting - into the strpbrk argument would produce false matches on input like non-numeric7.
If the format is always like this, then this could also work
#include <stdio.h>
int main()
{
char *str[] = {"a5 d8", "fe55 eec2", "a5 abc111"};
int num1, num2;
for (int i = 0; i < 3; i++) {
sscanf(str[i], "%*[^0-9]%d%*[^0-9]%d", &num1, &num2);
printf("num1: %d, num2: %d\n", num1, num2);
}
return 0;
}
Output
num1: 5, num2: 8
num1: 55, num2: 2
num1: 5, num2: 111
%[^0-9] will match any non digit character. By adding the * like this %*[^0-9] indicates that the data is to be read from the string, but ignored.
I suggest you write the logic on your own. I know, it's like reinventing the wheel, but in that case, you will have an insight into how the library functions actually work.
Here is a function I propose:
bool getNumber(str,num_ptr)
char* str;
long* num_ptr;
{
bool flag = false;
int i = 0;
*num_ptr = 0;
char ch = ' ';
while (ch != '\0') {
ch = *(str + i);
if (ch >= '0' && ch <= '9') {
*num_ptr = (*num_ptr) * 10 + (long)(ch - 48);
flag = true;
}
i++;
}
return flag;
}
Don't forget to pass a string with a \0 at the end :)
(i'm french, sorry for my bad english)
I don't know how to get an int from a char[], the patern of the char will be the same everytime : "prendre 2", "prendre 44", "prendre 710"...
I want to check if the pattern of the sentence is correct and get the integer.
I have try to do this, but as you see, the problem is i just can check if the integer is between 0-9 because I check only one char.
[...]
else if (est_prendre(commande)){
/* if the output is 1*/
int number = commande[8]- '0'
}
int est_prendre(char *commande){
int i;
char temp[9] = "";
char c = commande[8];
int num = c - '0';
for (i=0; i<8; i++){
temp[i] = commande[i];
}
if (strcmp ("prendre ", temp) == 0)
{
if ( /* num IS INTEGER? */)
{
return 1;
}
else
{
return 0;
}
} else {
return 0;
}
}
I expect if commande = "prendre 3", output of est_prendre is 1 because the pattern is correct
And after than to put the integer into the variable number.
Thank You!
Assuming that 'commande + 8' is a valid substring, what you need is atoi() function (ASCII to Integer). This function is widely documented, and you can easily find online its usage.
int number = atoi(commande+8);
Just remember that the substring terminates at the first non-digit character:
atoi("23") returns 23
atoi("51hh37") returns 51
atoi("z3456") returns 0
Note: atoi converts input string into integer, and you can use it if you are sure it fits expected input. So, if you expect to have either long integers or float values in your string you can use atol() (ASCII to long) or atof() (ASCII to float).
This is very basic, you should (re)read any reference/tutorial on C that you have used to learn the language.
You should just use the sscanf() standard function:
int value;
if (sscanf(commande, "prendre %d", &value) == 1)
{
... it was a match, the variable 'value' will be set to the number from the string
}
you can delete the (strange-looking) code that copies characters from commande to temp, and the temp variable too of course. Just inspect the commande string directly.
I want to write a C program which will take an IP address from the user like "112.234.456.789" in a string and give formatted output in addition of each block in string, e.g., "04.09.15.24" for the above IP address. Here's what I have so far:
#include<stdio.h>
#include<string.h>
#include<conio.h>
main()
{
char s[15],d[11];
int i=0,c = 0, sum[4] = {0};
d[i]=sum[c]/10;
printf("Enter ip address:");
gets(s);
printf("\n \n %s",s);
i=0;
for(c=0;c<15;c++)
{
if(s[c]!='.'||s[c]!='\0')
sum[i]=(s[c]-48)+sum[i];
else
i++;
}
for(i=0,c=0;c<4;c++,i+=3)
{
d[i]=(sum[c]/10)+48;
d[i+1]=sum[c]%10+48;
d[i+2]='.';
}
printf("\n \n %s",d);
getch();
}
The input should be an IP address like "112.234.546.234", and the output should be the result of adding the digits in each block, "04.09.15.06". The input and output should be in strings.
The problem with your code is that s[c]!='.'||s[c]!='\0' is going to evaluate true for any character in the input -- even '.'. This means i is never incremented, and ot only is every digit is summed to sum[0], but so is '.' - 48.
What you meant was s[c] != '.' && s[c] != '\0'.
I wrote the function you desire here.
#include <stdio.h>
#include <ctype.h>
void convert(const char *in, char *out) {
unsigned int sum = 0;
char ch;
do {
ch = *in++;
if (isdigit(ch)) {
sum += ch - '0';
} else {
*out++ = sum / 10 + '0';
*out++ = sum % 10 + '0';
if (ch == '.') {
*out++ = '.';
sum = 0;
}
}
} while (ch);
}
By the way, each "block" of the IPv4 address is an octet, and what you are doing is replacing each with its digit sum.
I just code you a simple example of how to "discard" unwanted characters.
#include <studio.h>
main ()
{
int add1, add2, add3, add4;
printf("enter an ip in the form xxx.xxx.xxx.xxx: )";
scanf("%d%*c%d%*c%d%*c%d", &add1, &add2, &add3, &add4);
printf("add1 = %d add2 = %d add3 = %d add4 = %d\n\n", add1, add2, add3, add4);
return 0;
}
console output:
enter a ip in the form xxx.xxx.xxx.xxx: 123.321.456.654
add1 = 123 add2 = 321 add3 = 456 add4 = 654
EDIT: you just have to play along with the "add#" variables to do your math thing.
It looks like homework (if this is the case, please tag it as homework), so I am going to give a few pointers:
Use fgets to read the input from the user. Read the input into a string.
Use sscanf to parse the string. Since you know there will be four positive integers, use "%u.%u.%u.%u" as the format string.
For each one of the four integers, compute the sum of the digits (using division by 10 and remainder by 10, as you just did).
Print the formatted output using printf (or snprintf to print to a string). If you want each sum to be formatted as a two-digits integer, with leading 0, use "%02u" as format specifier.
P.S. Be careful with snprintf, it might bite.
Other tips
Focus on one step at a time. Divide and conquer. Write a digit_sum function, taking an integer as argument, which computes the sum of its digits:
unsigned int digit_sum(unsigned int n)
{
unsigned int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
return sum;
}
Once your digit_sum function is working well, proceed with the main task.
I'm looking to read in a number from the keyboard and then I have to manipulate each digit individually (it's an Octal to Decimal converter).
Is there something similar to the charAt() method from Java that can be used to work with s particular digit?
I currently have the below code (incomplete) but when compiling, it returns "error: subscripted value is neither array nor pointer"
#include <stdio.h>
#include <math.h>
#include <string.h>
int main()
{
printf("Please enter an octal number ending with #");
char nextNum = getchar();
char number;
int counterUp = 0; //Records how many digits are entered
int counterDown = 1; //Records progress during conversion
int decimalNumber = 0;
while(nextNum != '#') //reads in the whole number, putting the characters together to form one Octal number.
{
number = (number + nextNum);
counterUp++;
nextNum = getchar();
}
//Begin converson from Octal to Decimal
while(counterUp >= 0)
{
int added = (number[counterUp] * (pow(8, counterDown)));
decimalNumber = (decimalNumber + added);
counterDown++;
}
}
I'm not looking to be told how to go from octal to decimal, just how to work with one digit at a time.
Use fgets() instead of a single char:
char number[25]; // max of 25 characters in string
fgets(number, 24, stdin); // read a line from 'stdin', with a max of 24 characters
number[24] = '\0'; // append the NUL character, so that we don't run into problems if we decide to print the string
Now you can subscript number at will, e.g. number[10] = 'A'.
I think you're used to Java way where you can write something like:
String number = "";
number += "3";
number += "4";
Strings in C do not work like that. This code doesn't do what you think it does:
char number = 0; // 'number' is just a one-byte number
number += '3'; // number now equals 51 (ASCII 3)
number += '4'; // number now equals 103 (meaningless)
Maybe something like this will work for you:
char number[20];
int i = 0;
number[i++] = '3';
number[i++] = '4';
Or, you could simply use scanf to read a number in from the keyboard.
I recommend that you find a good book about C and read about strings first, then scanf second.
I think you need to step back and look at your algorithm more closely.
What does char number store? What do you expect this loop to do:
while(nextNum != '#') //reads in the whole number, putting the characters together to form one Octal number.
{
number = (number + nextNum);
counterUp++;
nextNum = getchar();
}
In particular, what does number = (number + nextNum); mean?
You need to define number as an array of chars.
e.g.
char number[16];
Then change your reading loop to append to the array.
while(nextNum != '#')
{
number[counterUp] = nextNum;
counterUp++;
nextNum = getchar();
}
I have a string that has 0111111100000000000000000000101
I wanted to convert this to hex, so I used the code below
int assembledHex;
sscanf(buffer, "%x", &assembledHex);
printf("this is the assembled hex %x\n",assembledHex);
but when I print it, it gives me 101. I thought sscanf can convert to hex from a string, what am I doing wrong and how can I fix it. The result I want is 0x3F800005
This is not checked or anything, and also quite slow, but it's a quick start:
unsigned int bin_to_int(const char *s) {
int i;
unsigned int result;
result = 0;
if (s[0] == '1') result++;
for (i = 1; i < strlen(s); i++) {
result <<= 1;
if (s[i] == '1') {
result++;
}
}
return result;
}
Your sscanf is reading the string as HEX, but the string is written in binary. You get "101" because int can only store the first 8 digits - each digit is 4 bits, so two digits=8 bits=1 byte, and 8 digits are 4 bytes, which is the size of int. So you actually store "00000101", buy printf does not print the leading zeroes so you get "101".