Can you put an integer from a variable, for example:
int i=17;
char array[]= i;
and now i want to have
array[3]= {1,7,\0}
I know it doesn't work this way but i dont know how to do it without some special functions, which i dont want to use. Thank you for your help.
this is what i came up with:
char array[];
int counter = 172; //the number i want to put into string
int i= 0;
int p=0;
float c = counter;
int k=0, g=0, h=0;
while(counter !=0){
counter = counter /10;
c= c/10;
p++;
}
while(p !=0){
c=c*10;
k=c;
h= k-g;
g=k*10;
array[i] = h;
i++;
p--;
}
array[i]= '\0';
Use sprintf(buffer, "%d", i);
Make sure that buffer is long enough to contain any possible number-string and the terminating \0 byte.
sprintf accepts everything that printf does, but sends its output to a string buffer instead of STDOUT.
If you really don't want to use sprintf, then here is a sample code snippet for you.
#define BASE 10
#define MAXLEN 10
int val = 153;
char valstr[MAXLEN];
//Reverse the int
int valcpy = val;
int valrev = 0;
while(valcpy) {
valrev *= BASE;
valrev += valcpy % BASE;
valcpy /= BASE;
}
//Convert to string
int i = 0;
while(valrev) {
valstr[i] = valrev % BASE + '0';
valrev /= BASE;
i++;
}
valstr[i] = '\0';
printf("%d = %s", val, valstr); //prints 153 = 153
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I need to convert integer to a string, be it negative or positive.
So far i able to convert positive integers to strings using the following code.
But not the negative ones. How can i handle them properly to convert them to strings.
Here is the code that i was using.
Thanks
Rajat!
/*
* C Program which Converts an Integer to String & vice-versa
*/
#include <stdio.h>
#include <string.h>
#include <math.h>
void tostring(char [], int);
int main()
{
char str[10];
int num, result;
printf("Enter a number: ");
scanf("%d", &num);
tostring(str, num);
printf("Number converted to string: %s\n", str);
return 0;
}
void tostring(char str[], int num)
{
int i, rem, len = 0, n;
if(num<0)
{
n=(-1)*(num);
}
else
{
n=num;
}
while (n != 0)
{
len++;
n /= 10;
}
for (i = 0; i < len; i++)
{
rem = num % 10;
num = num / 10;
str[len - (i + 1)] = rem + '0';
}
str[len] = '\0';
}
Before doing anything else, see if n is negative. If it is, start the output with the sign - (make sure len is also one more than it would be otherwise, and that your stringification starts one character later), make n positive, and continue as you were doing it before.
You have to be really wary of "corner-case" like many other have said :
You can't have the positive value of a negative int in an int
The range value of an int is [MIN; +MIN -1], like –2,147,483,648 to 2,147,483,647 for a 4 byte int.
So, if you have –2,147,483,648 and you *-1, you will not have 2,147,483,648 since it will overflow the int capacity
Your loop for finding the len of int is "bad", because you don't take negative number in count (but I suppose this is the purpose of this post) and you don't take car of the corner case 0 ("len" value is 0 but must be 1).
So, how can you make this function ?
1 : Fix the int len calculation
size_t len = 1;
for (int n = number; n <= -10 || 10 <= n; n /= 10) {
++len;
}
2 : Fix the "digit to char" loop
for (size_t i = 0; i < len; ++i) {
str[len - i - 1] = abs(number % 10) + '0';
number /= 10;
}
str[len] = '\0';
There. The only thing that left is to put "-" in the beginning and have an offset for negative case number.
You can have an offset variable (fix the "digit to char loop" if you use it) or you can simply do "++str".
There, you can do the function on your own now, I pratically gived you the answer.
On a funny note, you can skip the "abs" function if you simply do the following :
void tostring(char *str, int number)
{
char *digit = "9876543210123456789" + 9;
size_t len = 1;
if (number < 0) {
// TODO : Put '-' in the first case
// TODO : Make str to be *str[1]
}
for (int n = number; n <= -10 || 10 <= n; n /= 10) {
++len;
}
for (size_t i = 0; i < len; ++i) {
str[len - i - 1] = digit[number % 10];
number /= 10;
}
str[len] = '\0';
}
If you don't understand how this work, take your time and read how pointer work (especially pointer arithmetic).
I have solved the issue by the help from #Amadan .
Here is the code that i am using. Please feel free to tell me a more better way to solve this issue.
Thanks
Rajat
/*
* C Program which Converts an Integer to String & vice-versa
*/
#include <stdio.h>
#include <string.h>
#include <math.h>
void tostring(char [], int);
int main()
{
char str[10];
int num, result;
printf("Enter a number: ");
scanf("%d", &num);
tostring(str, num);
printf("Number converted to string: %s\n", str);
return 0;
}
void tostring(char str[], int num)
{
int i, rem, len = 0, n;
bool flag=0;
if(num<0)
{
n=-num;
flag=1;
}
else
{
n=num;
flag=0;
}
while (n != 0)
{
len++;
n /= 10;
}
if(flag==1)
{
num=-1*num;
str[0]='-';
}
for (i = 0; i < len; i++)
{
rem = num % 10;
num = num / 10;
if(flag==1)
{
str[len - (i)] = rem + '0';
}
else
{
str[len - (i + 1)] = rem + '0';
}
}
if(flag==1)
{
str[len+1] = '\0';
}
else
{
str[len] = '\0';
}
}
Just use sprintf function as below,
sprintf(str,"%i",num);
So the modified code will be,
#include <stdio.h>
#include <string.h>
#include <math.h>
void tostring(char [], int);
int main()
{
char str[10];
int num, result;
printf("Enter a number: ");
scanf("%d", &num);
//tostring(str, num);
sprintf(str,"%i",num);
printf("Number converted to string: %s\n", str);
return 0;
}
void tostring(char str[], int num)
{
int i, rem, len = 0, n;
n =num;
while (n != 0)
{
len++;
n /= 10;
}
for (i = 0; i < len; i++)
{
rem = num % 10;
num = num / 10;
str[len - (i + 1)] = rem + '0';
}
str[len] = '\0';
}
Hope this helps.
Here you have the function which works with any base (you need just to find enough chars to represent digits) but it will not work in one corner case (can you find the case?)
static const char Digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUWXYZ";
static char *reverse(char *s, size_t len)
{
size_t pos;
for(pos = 0; pos < len / 2; pos++)
{
char tmp = s[pos];
s[pos] = s[len - pos - 1];
s[len - pos - 1] = tmp;
}
return s;
}
char *toString(char *buff, int n, unsigned base)
{
int saved = n;
char *savedbuff = buff;
n = n < 0 ? -n : n; // <= there is one number which will cause problems. Which one?
do
{
*buff++ = Digits[n % base];
n /= base;
}while(n);
if(saved < 0) *buff++ = '-';
*buff = 0;
return reverse(savedbuff, buff - savedbuff);
}
int main()
{
char buff[50];
printf("%s\n", toString(buff, -255,12)); // 12 base :)
printf("%s\n", toString(buff, -976,10)); // 10 base
printf("%s\n", toString(buff, -976,8)); // or maybe octal ?
return 0;
}
I'm trying to turn an int into string. I did it so far by getting the int with scanf, and then split it according to it's digits, and then put every one of the digits inside int array. Then I want to put all the int arr values inside a string, where the sign + or - will be the first character. Here is my code:
#include <stdio.h>
#include <string.h>
#define LENGTH 50
int getLength(int num, int arr[]);
int main()
{
int num = 0, i = 0;
int arr[LENGTH] = {0};
char string[LENGTH] = {0};
printf("enter number: ");
scanf("%d", &num);
int sizeMe = getLength(num, arr);
string[2] = arr[2] + '0';
printf("length %d one of values: %c", sizeMe,string[2]);
for(i = 1; i < sizeMe + 1; i++);
{
string[i] = arr[sizeMe - i] + '0';
}
string[0] = '+';
string[sizeMe] = 0;
printf("string: %s", string);
}
int getLength(int num,int arr[])
{
int count = 0;
int i = 0, temp = 0;
while(num != 0)
{
temp = num%10;
num /= 10;
count++;
i++;
arr[i] = temp;
printf("index %d is %d\n",i,arr[i]);
}
return count;
}
The output of that program is just '+'. What did I do wrong here?
The problem that is causing your code not to work is that you have a semicolon after the for statement like this:
for(i = 1; i < sizeMe + 1; i++);
{
string[i] = arr[sizeMe - i] + '0';
}
That code would be equivalent to this:
for(i = 1; i < sizeMe + 1; i++){}
string[i] = arr[sizeMe - i] + '0';
So what's happening there is that only the last element of string is written in, the rest is left blank, which generates undefined behavior. To solve the problem, remove the semicolon. I also recommend putting the { at the end of the line of the for statement instead of on a new line since doing so would prevent you from making such mistakes. This is therefore the correct code, formatted in the way that I recommend formatting:
for(i = 1; i < sizeMe + 1; i++){
string[i] = arr[sizeMe - i + 1] + '0';
}
Note that you also forgot the +1 in arr[sizeMe - i + 1].
Although that was the error that made your code not work the way you wanted it to work, you've also made several other mistakes, which could potentially cause your program to crash.
First of all, in the for loop, you're not testing if i is greater than LENGTH. The problem with that is that if i is greater than LENGTH, string[i] will be outside of the array, which will cause buffer overflow and make your program crash. To solve this problem, add the following code inside your for loop:
if(i + 1 > LENGTH){
break;
}
The break statement will exit the for loop immediately. Note that we're testing if i + 1 is greater than LENGTH to leave space for the null character at the end of the string.
For the same reason, string[sizeMe] = 0; is also bad, since nothing says that sizeMe is less than the size of the array. Instead, use string[i] = 0;, since i has been incremented until it either reaches LENGTH or sizeMe. Therefore, i will be the minimum of these two values, which is what we want.
You also need to return something at the end of the main function. The main function is of type int, so it should return an int. In C++, this code wouldn't compile because of that. Your code compiled since you're using C and C compilers are generally more tolerant than C++ compilers, so you only got a warning. Make sure to fix all compiler warnings, since doing so can solve bugs. The warnings are there to help you, not to annoy you. Generally, the main function should return 0, since this value usually means that everything went well. So you need to add return 0; at the end of the main function.
Therefore, this is the code you should use:
#include <stdio.h>
#include <string.h>
#define LENGTH 50
int getLength(int num, int arr[]);
int main(){
int num = 0, i = 0;
int arr[LENGTH] = {0};
char string[LENGTH] = {0};
printf("enter number: ");
scanf("%d", &num);
int sizeMe = getLength(num, arr);
string[2] = arr[2] + '0';
printf("length %d one of values: %c", sizeMe,string[2]);
for(i = 1; i < sizeMe + 1; i++){
string[i] = arr[sizeMe - i + 1] + '0';
if(i + 1 > LENGTH){
break;
}
}
string[0] = '+';
string[i] = 0;
printf("string: %s", string);
return 0;
}
int getLength(int num,int arr[]){
int count = 0;
int i = 0, temp = 0;
while(num != 0){
temp = num%10;
num /= 10;
count++;
i++;
arr[i] = temp;
printf("index %d is %d\n",i,arr[i]);
}
return count;
}
Also, as some programmer dude pointed out in a comment, it's much easier to use sprintf. Then your code would be much simpler:
#include <stdio.h>
#include <string.h>
#define LENGTH 50
int main(){
int num = 0;
char string[LENGTH] = {0};
printf("enter number: ");
scanf("%d", &num);
sprintf(string, "%c%d", num >= 0 ? '+' : '-', num);
printf("string: %s", string);
return 0;
}
The short answer to turning a C int into a decimal string is to call sprintf(). That leads to the question how sprintf() does it.
From the book The C Programming Language, 2nd edition section 3.6. There is an example of a function that return a string representation of an integer. So here is the code:
void numberToString(int n, char *s){
int i, sign;
if ((sign = n) < 0) /*record sign*/
n = -n; /* make n positive */
i = 0;
do { // generate digits in reverse order
s[i++] = n % 10 + '0'; // get next digit*/
} while ((n /= 10) > 0); // delete it
s[i++] = sign < 0? '-': '+'; // or -- if(sign < 0) s[i++] = '-'; -- if you want just the sign '-'
s[i] = '\0';
strrev(s); //reverse the string
}
int main()
{
int n;
char str[LENGTH];
printf("Number: ");
scanf("%i", &n);
numberToString(n, str);
printf("Number as string: %s\n", str);
}
strrev is defined in the string.h header (so include it).
You can try and do this with sprintf. When you calculate the number length from get_length(), you can declare a string buffer, either statically or dynamically. Once declared, you can send the formatted output in the buffer with sprintf().
However, if you wish to still use your approach, #Donald Duck has covered the issues into debugging your code, and this is just another approach you can use if you want to.
Here is an example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
size_t get_length(int number);
int main(void) {
int number;
size_t numcnt;
char *string;
printf("Enter number: ");
if (scanf("%d", &number) != 1) {
printf("Invalid number entered\n");
exit(EXIT_FAILURE);
}
printf("Number = %d\n", number);
numcnt = get_length(number);
string = malloc(numcnt+1);
if (!string) {
printf("Cannot allocate %zu bytes for string\n", numcnt+1);
exit(EXIT_FAILURE);
}
sprintf(string, "%d", number);
printf("String = %s\n", string);
free(string);
return 0;
}
size_t get_length(int number) {
size_t count = 0;
if (number < 0) {
number *= -1;
count++;
}
for (size_t i = number; i > 0; i /= 10) {
count++;
}
return count;
}
Sample input 1:
Enter number: 1234
Sample output 1:
Number = 1234
String = 1234
Sample input 2:
Enter number: -1234
Sample output 2:
Number = -1234
String = -1234
i'm a beginner and my english is not well so sorry first. im trying to sum the numbers in a string (for a14fg5pk145 it returns 14+5+145), and it doesn't work:
"Exception thrown: read access violation.
str was 0x61."
this i my code:
void main()
{
int x, i;
char* pp;
char buffer[SIZE];
printf("Please enter numbers and letters:\n");
gets(buffer);
pp = buffer;
x = SumStr(*pp);
printf("%d", x);
}
int SumStr(char* str)
{
int sum=0, num=0, flag = 0;
while ((*str) != '\0')
{
while (((*str) > '1') && ((*str) < '9'))
{
if (flag == 0)
{
num += (*str);
flag = 1;
}
else if (flag == 1)
num = num * 10 + (*str);
str++;
}
if (flag == 0)
str++;
sum += num;
num = 0;
flag = 0;
}
return sum;
}
First problem with your code which is causing Exception.
x = SumStr(*pp);
it should be
x = SumStr(pp);
Because you should pass address of the string pointer not its first character by attaching asterix.
Second Issue that will not make it work is.
num += (*str);
and
num = num * 10 + (*str);
By (*str) you are actually adding the character ascii value instead of number.
This will solve the problem by changing the ascii value to number.
num += (*str) - '0';
num = num * 10 + (*str) - '0';
This may serve your purpose
#include<stdio.h>
#include<string.h>
int main()
{
int i, sum = 0, store;
char str[] = "a14fg5pk145asdasdad6";
int length = strlen(str);
for(i = 0; i < length; i++) {
store = 0;
while(isdigit(str[i])) {
store = (store * 10) + (str[i] - '0');
i++;
}
sum += store;
}
printf("%d\n", sum);
return 0;
}
output :
170
Pass pp, not *pp, to the function SumStr. *pp has the type char, and the function expects char *. In fact, you do not even need pp at all, just pass the buffer as the parameter.
Also:
Never use gets(). Because it is impossible to tell without knowing the
data in advance how many characters gets() will read, and because
gets() will continue to store characters past the end of the buffer, it
is extremely dangerous to use. It has been used to break computer
security. Use fgets() instead.
void main(){
int digits[21]; //this was initialized so that every element is 0 by looping over every element and setting it to 0
char input[20];
scanf("%s", input);
parseDigits(digits, input);
}
void parseDigits(int* digits, char *string){
char *end = string + strlen(string) -1;
int i;
for (i = 0; i < strlen(string) - 1; i++, end--){
int *digit = digits + i;
printf("%d", *digit);
*digit += charToDigit(*end);
if (*digit >= 10){ //carry one
*digit -= 10;
digit++;
*digit += 1;
}
}
}
Prints an excessively large integer, instead of 0, which is the expected output. I don't understand since
digits + i
should still be within the range of the array.
There can be other issues, but from first glance you have not initialized your array properly, which should have been done like:
int digits[21] = { 0 };
I have an assignment where I need to print an integer in C without using printf, putchar, etc. No header files allowed to be included. No function calls except for anything I wrote. I have one function my_char I am using (maybe its wrong) but it prints out a character. I currently have the following code which is printing the number out backwards. Not looking for an answer. Just looking for some direction, some help, maybe I'm looking at it completely wrong.
void my_int(int num)
{
unsigned int i;
unsigned int j;
char c;
if (num < 0)
{
my_char('-');
num = -num;
}
do
{
j = num % 10;
c = j + '0';
my_char(c);
num = num/10;
}while(num >0);
}
Instead of calling my_char() in the loop instead "print" the chars to a buffer and then loop through the buffer in reverse to print it out.
Turns out you can't use arrays. In which case you can figure out the max power of 10 (ie log10) with the loop. Then use this to work backwards from the first digit.
unsigned int findMaxPowOf10(unsigned int num) {
unsigned int rval = 1;
while(num) {
rval *= 10;
num /= 10;
}
return rval;
}
unsigned int pow10 = findMaxPowOf10(num);
while(pow10) {
unsigned int digit = num / pow10;
my_char(digit + '0');
num -= digit * pow10;
pow10 /= 10;
}
One option might be to do this recursively, so the number gets printed out in the right order.
In this case, instead of a do/while loop, you'd have a construction more like this, with a base case of num=0.
if(num==0)
return;
j = num % 10;
c = j + '0';
my_int(num/10);
my_char(c);
Edit: Noticed that you aren't allowed to use recursion. It's a bit ugly, but you could check for the digits in the number, and then loop backwards across the number.
To find the number of digits,
int digitDivide = 1;
int tempNum = num;
while(tempNum>0){
tempNum= tempNum/10;
digitDivide=digitDivide*10;
}
and then use that to loop through the number as follows:
digitDivide = digitDivide/10;
while(digitDivide>0){
tempNum = (num/digitDivide)%10;
c = j + '0';
my_char(c);
digitDivide=digitDivide/10;
}
You can convert an int to char * , char * and display this char* :
char *put_int(int nb)
{
char *str;
str = malloc(sizeof(char) * 4);
if (str == NULL)
return (0);
str[0] = (nb / 100) + '0';
str[1] = ((nb - ((nb / 100 * 100 )) / 10) + '0');
str[2] = ((nb % 10) + '0');
return (str);
}
void put_str(char *str)
{
while (*str)
write(1, str++,1);
}
int main(void)
{
put_str(put_int(42));
return (0);
}