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
Related
While doing reverse program in C,I am getting issue with number 01 & 10 because its reverse is not showing in the output. Here is my code:
#include<stdio.h>
int main(){
int i,n,rev=0;
printf("Enter the number:");
scanf("%d",&n);
while(n>0){
i=n%10;
rev=rev*10+i;
n=n/10;
}
printf("Reverse of that number:%d",rev);
return 0;
}
I am expecting that if I give 01 as input, its reverse must be shown as 10.
If obliged to still use "%d":
Detect the input offset with "%n", which stores the character offset of the scan at that point.
int offset1 = 0;
int offset2 = 0;
if (scanf(" %n%d%n", &offset1, &n, &offset2) == 1) {
while (offset1 < offset2) {
offset1++;
i = n%10;
rev = rev*10+i;
n = n/10;
}
offset2 - offset1 will be the character count of the number and input "01" has a character count of 2.
This still gets fooled if the text input includes a sign character. Additional, and not so clear, code needed to handle that.
As suggested in comments, this is trivial if approached from a string perspective.
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char input[100] = {0};
if (scanf("%99s", input) != 1) {
printf("Invalid input.\n");
return 1;
}
size_t len = strlen(input);
char *output = malloc(len + 1);
size_t i;
for (i = 0; i < len; i++) {
output[i] = input[len-i-1];
}
output[i] = '\0';
printf("%s\n", output);
free(output);
return 0;
}
You could add in validation code that determines that the input actually is a valid integer, and if you actually need an int back, there are library functions like strtol that will accomplish this.
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 am self teaching C programming.
I am trying to count number of int present in given string which are separated by space.
exp:
input str = "1 2 11 84384 0 212"
output should be: 1, 2, 11, 84384, 0, 212
total int = 6
When I try. It gives me all the digits as output which make sense since I am not using a right approach here.
I know in python I can use str.split (" ") function which can do my job very quickly.
But I want to try something similar in C. Trying to create my own split method.
#include <stdio.h>
#include <string.h>
void count_get_ints(const char *data) {
int buf[10000];
int cnt = 0, j=0;
for (int i=0; i<strlen(data); i++) {
if (isspace(data[i] == false)
buf[j] = data[i]-'0';
j++;
}
printf("%d", j);
}
// when I check the buffer it includes all the digits of the numbers.
// i.e for my example.
// buf = {1,2,1,1,8,4,3,8,4,0,2,1,2}
// I want buf to be following
// buf = {1,2,11,84384,0,212}
I know this is not a right approach to solve this problem. One way to keep track of prev and dynamically create a memory using number of non space digits encountered.
But I am not sure if that approach helps.
You want to build your number incrementally until you hit a space, then put that into the array. You can do this by multiplying by 10 then adding the next digit each time.
void count_get_ints(const char *data) {
int buf[10000];
int j = 0;
int current_number = 0;
// Move this outside the loop to eliminate recalculating the length each time
int total_length = strlen(data);
for (int i=0; i <= total_length; i++) {
// Go up to 1 character past the length so you
// capture the last number as well
if (i == total_length || isspace(data[i])) {
// Save the number, and reset it
buf[j++] = current_number;
current_number = 0;
}
else {
current_number *= 10;
current_number += data[i] - '0';
}
}
}
I think strtok will provide a cleaner solution, unless you really want to iterate over every char in the string. It has been a while since I did C, so please excuse any errors in the code below, hopefully it will give you the right idea.
#include <stdio.h>
#include <stdlib.h>
int main() {
char str[19] = "1 2 11 84384 0 212";
const char s[2] = " ";
char *token;
int total;
total = 0;
token = strtok(str, s);
while (token != NULL) {
printf("%s\n", token);
total += atoi(token);
token = strtok(NULL, s);
}
printf("%d\n", total);
return 0;
}
You can check the ascii value of each character by doing c-'0'. If it's between [0,9], then it's an integer. By having a state variable, when you're inside an integer by checking if a given character is a number of space, you can keep track of the count by ignoring white space. Plus you don't need a buffer, what happens if data is larger than 10,000, and you write pass the end of the buffer?, undefined behavior will happen. This solution doesn't require a buffer.
Edit, the solution now prints the integers that are in the string
void count_get_ints(const char *data) {
int count = 0;
int state = 0;
int start = 0;
int end = 0;
for(int i = 0; i<strlen(data); i++){
int ascii = data[i]-'0';
if(ascii >= 0 && ascii <= 9){
if(state == 0){
start = i;
}
state = 1;
}else{
//Detected a whitespace
if(state == 1){
count++;
state = 0;
end = i;
//Print the integer from the start to end spot in data
for(int j = start; j<end; j++){
printf("%c",data[j]);
}
printf(" ");
}
}
}
//Check end
if(state == 1){
count++;
for(int j = start; j<strlen(data); j++){
printf("%c",data[j]);
}
printf(" ");
}
printf("Number of integers %d\n",count);
}
I believe the standard way of doing this would be using sscanf using the %n format specifier to keep track of how much of the string is read.
You can start with a large array to read into -
int array[100];
Then you can keep reading integers from the string till you can't read anymore or you are done reading 100.
int total = 0;
int cont = 0;
int ret = 1;
while(ret == 1 && total < 100) {
ret = sscanf(input, "%d%n", &array[total++], &cont);
input += cont;
}
total--;
printf("Total read = %d\n", total);
and array contains all the numbers read.
Here is the DEMO
Example using strtol
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <errno.h>
#include <ctype.h>
int count_get_ints(int output[], int output_size, const char *input) {
const char *p = input;
int cnt;
for(cnt = 0; cnt < output_size && *p; ++cnt){
char *endp;
long n;
errno = 0;
n = strtol(p, &endp, 10);
if(errno == 0 && (isspace((unsigned char)*endp) || !*endp) && INT_MIN <= n && n <= INT_MAX){
output[cnt] = n;
while(isspace((unsigned char)*endp))
++endp;//skip spaces
p = endp;//next parse point
} else {
fprintf(stderr, "invalid input '%s' in %s\n", p, __func__);
break;
}
}
return cnt;
}
int main(void) {
const char *input = "1 2 11 84384 0 212";
int data[10000];
int n = sizeof(data)/sizeof(*data);//number of elements of data
n = count_get_ints(data, n, input);
for(int i = 0; i < n; ++i){
if(i)
printf(", ");
printf("%d", data[i]);
}
puts("");
}
Assuming you don't have any non-numbers in your string, you can just count the number of spaces + 1 to find the number of integers in the string like so in this pseudo code:
for(i = 0; i < length of string; i++) {
if (string x[i] == " ") {
Add y to the list of strings
string y = "";
counter++;
}
string y += string x[i]
}
numberOfIntegers = counter + 1;
Also, this reads the data between the white spaces. Keep in mind this is pseudo code, so the syntax is different.
So I have an assignment where I should delete a character if it has duplicates in a string. Right now it does that but also prints out trash values at the end. Im not sure why it does that, so any help would be nice.
Also im not sure how I should print out the length of the new string.
This is my main.c file:
#include <stdio.h>
#include <string.h>
#include "functions.h"
int main() {
char string[256];
int length;
printf("Enter char array size of string(counting with backslash 0): \n");
/*
Example: The word aabc will get a size of 5.
a = 0
a = 1
b = 2
c = 3
/0 = 4
Total 5 slots to allocate */
scanf("%d", &length);
printf("Enter string you wish to remove duplicates from: \n");
for (int i = 0; i < length; i++)
{
scanf("%c", &string[i]);
}
deleteDuplicates(string, length);
//String output after removing duplicates. Prints out trash values!
for (int i = 0; i < length; i++) {
printf("%c", string[i]);
}
//Length of new string. The length is also wrong!
printf("\tLength: %d\n", length);
printf("\n\n");
getchar();
return 0;
}
The output from the printf("%c", string[i]); prints out trash values at the end of the string which is not correct.
The deleteDuplicates function looks like this in the functions.c file:
void deleteDuplicates(char string[], int length)
{
for (int i = 0; i < length; i++)
{
for (int j = i + 1; j < length;)
{
if (string[j] == string[i])
{
for (int k = j; k < length; k++)
{
string[k] = string[k + 1];
}
length--;
}
else
{
j++;
}
}
}
}
There is a more efficent and secure way to do the exercise:
#include <stdio.h>
#include <string.h>
void deleteDuplicates(char string[], int *length)
{
int p = 1; //current
int f = 0; //flag found
for (int i = 1; i < *length; i++)
{
f = 0;
for (int j = 0; j < i; j++)
{
if (string[j] == string[i])
{
f = 1;
break;
}
}
if (!f)
string[p++] = string[i];
}
string[p] = '\0';
*length = p;
}
int main() {
char aux[100] = "asdñkzzcvjhasdkljjh";
int l = strlen(aux);
deleteDuplicates(aux, &l);
printf("result: %s -> %d", aux, l);
}
You can see the results here:
http://codepad.org/wECjIonL
Or even a more refined way can be found here:
http://codepad.org/BXksElIG
Functions in C are pass by value by default, not pass by reference. So your deleteDuplicates function is not modifying the length in your main function. If you modify your function to pass by reference, your length will be modified.
Here's an example using your code.
The function call would be:
deleteDuplicates(string, &length);
The function would be:
void deleteDuplicates(char string[], int *length)
{
for (int i = 0; i < *length; i++)
{
for (int j = i + 1; j < *length;)
{
if (string[j] == string[i])
{
for (int k = j; k < *length; k++)
{
string[k] = string[k + 1];
}
*length--;
}
else
{
j++;
}
}
}
}
You can achieve an O(n) solution by hashing the characters in an array.
However, the other answers posted will help you solve your current problem in your code. I decided to show you a more efficient way to do this.
You can create a hash array like this:
int hashing[256] = {0};
Which sets all the values to be 0 in the array. Then you can check if the slot has a 0, which means that the character has not been visited. Everytime 0 is found, add the character to the string, and mark that slot as 1. This guarantees that no duplicate characters can be added, as they are only added if a 0 is found.
This is a common algorithm that is used everywhere, and it will help make your code more efficient.
Also it is better to use fgets for reading input from user, instead of scanf().
Here is some modified code I wrote a while ago which shows this idea of hashing:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define NUMCHAR 256
char *remove_dups(char *string);
int main(void) {
char string[NUMCHAR], temp;
char *result;
size_t len, i;
int ch;
printf("Enter char array size of string(counting with backslash 0): \n");
if (scanf("%zu", &len) != 1) {
printf("invalid length entered\n");
exit(EXIT_FAILURE);
}
ch = getchar();
while (ch != '\n' && ch != EOF);
if (len >= NUMCHAR) {
printf("Length specified is longer than buffer size of %d\n", NUMCHAR);
exit(EXIT_FAILURE);
}
printf("Enter string you wish to remove duplicates from: \n");
for (i = 0; i < len; i++) {
if (scanf("%c", &temp) != 1) {
printf("invalid character entered\n");
exit(EXIT_FAILURE);
}
if (isspace(temp)) {
break;
}
string[i] = temp;
}
string[i] = '\0';
printf("Original string: %s Length: %zu\n", string, strlen(string));
result = remove_dups(string);
printf("Duplicates removed: %s Length: %zu\n", result, strlen(result));
return 0;
}
char *remove_dups(char *str) {
int hash[NUMCHAR] = {0};
size_t count = 0, i;
char temp;
for (i = 0; str[i]; i++) {
temp = str[i];
if (hash[(unsigned char)temp] == 0) {
hash[(unsigned char)temp] = 1;
str[count++] = str[i];
}
}
str[count] = '\0';
return str;
}
Example input:
Enter char array size of string(counting with backslash 0):
20
Enter string you wish to remove duplicates from:
hellotherefriend
Output:
Original string: hellotherefriend Length: 16
Duplicates removed: helotrfind Length: 10
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.