i was wondering how to strip off digits one by one and store them into an array so i can sort them. For example if the user entered 7216. take the 7 stor into cell one, take 2 store it cell 3 ettc and then sort it so it looks like this 1267 and then output it back as a whole number instead of segments in other words tak 1 2 6 7 and concatenate it so it looks like 1267 whic is one thosand two hundred sixty seven. i'm not sure if i need a loop or not.

i was tinking something like this:

if(n < 10)
store n in tan array
else
n/10 store in array
n % 10 store it in an array until done
if any one can clear this up i'd greatly appreciate, i know how to sort it i already wrote the sort and tested it on ints and that works fine, just need a way of stripping each digit one by one and storing into an array.

Recommended Answers

All 12 Replies

Just showing you how to extract digits one by one from an int

#include<stdio.h>

int main()
{
  unsigned input, temp;
  printf("\nEnter int: ");
  scanf("%u",&input);
  temp = input;
  do
  {
	printf("%i\n",(temp % 10));
	}while((temp = temp/10) > 0);
	
}

And how to combine the digits stored in a string into an int

#include <stdio.h>
#include <string.h>
#include<math.h>

int main()
{
	char a[10];
	int i, size;
	int value = 0;
	printf("\nEnter string: ");
	scanf("%s",a);
	size = strlen(a) - 1;
	for(i = 0;i <= size ; ++i)
		value += (a[i] - '0') * pow(10,size - i);
	printf("int: %i ", value);
}

Alternatively you can use the functions itoa and atoi respectively.

>Alternatively you can use the functions itoa and atoi respectively.
itoa isn't a standard function, so it may not be available.

itoa isn't a standard function, so it may not be available.
>>Hmmm, I just checked it and you are right. I wasn't aware of that.
I tried to investigate the reason behind it and found this.

It really widened my knowledge. But could you tell me what is the most common implementation of itoa if it's there? I guess it's using static arrays, right?

>But could you tell me what is the most common implementation of itoa if it's there?
sprintf:

#include <stdio.h>

int main ( void )
{
  char buffer[20];

  sprintf ( buffer, "%d", 12345 );
  printf ( "%s\n", buffer );

  return 0;
}

There's really no good reason to write itoa manually because the common definition isn't nearly as flexible as sprintf, but to do it more right than just about every example you're likely to find:

/* K&R pp.64, modified */
#include <stdlib.h>
#include <string.h>

void rev_str ( char *s )
{
  size_t i = 0;
  size_t j = strlen ( s ) - 1;

  while ( i < j ) {
    char save = s[i];
    s[i++] = s[j];
    s[j--] = save;
  }
}

void my_itoa ( int n, char *s )
{
  int i = 0;
  int sign = n;

  do
    s[i++] = (char)abs ( n % 10 ) + '0';
  while ( n /= 10 );

  if ( sign < 0 )
    s[i++] = '-';

  s[i] = '\0';

  rev_str ( s );
}

Most examples out there can't handle the smallest negative value on two's complement machines.

The common definition of itoa also handles conversion to other bases and returns the buffer. Changes to get this effect are minor:

char *my_itoa ( int value, char *buffer, int radix )
{
  int i = 0;
  int sign = value;
  const char *digit = "0123456789ABCDEF";

  do
    buffer[i++] = digit[abs ( value % radix )];
  while ( value /= radix );

  if ( sign < 0 )
    buffer[i++] = '-';
  buffer[i] = '\0';

  rev_str ( buffer );

  return buffer;
}

I see. Thanks Narue. I really appreciate this.

In your first example you used sprintf:

#include <stdio.h>

int main ( void )
{
  char buffer[20];

  sprintf ( buffer, "%d", 12345 );
  printf ( "%s\n", buffer );

  return 0;
}

If I were to write a function my_itoa using sprintf:

#include <stdio.h>

char *my_itoa (int n )
{
  char buffer[20];

  sprintf ( buffer, "%d", n );
  return buffer;

  return 0;
}

But then I should be using static char buffer instead of automatic char buffer, right?

And the thing is I have used itoa before in my old turbo C compiler and i just needed to pass only one parameter through it and that is just the int. I just wanted to know if it used static array of char or an automatic one. However, in my current borland 5.5 itoa() takes 3 inputs, so i guess it works like the last example you provided.

And also one thing I wrote a lot of program that returned a local automatic array of something. Like

char *func(int n)
{
    char a[10];
    //code
    return  a;
}

I guess it's wrong, right? Especially if I try to use the pointer returned by the function some time later. I made a lot of function like this and mainly used them in this way

cout<<func(n);

Is it a valid use? Please verify me.

>But then I should be using static char buffer instead of automatic char buffer, right?
You should avoid static buffers, they limit the flexibility of a function because they're not reentrant, or thread safe, and the buffer is rewritten for subsequent calls. It's better to either have the caller take responsibility and pass a buffer, or return a pointer to dynamically allocated memory. The former is the better option because it makes it easier to ensure that memory is released. If the caller is forced to allocate memory for a buffer, chances are better that the caller will also remember to release it properly. That's not the case when memory is allocated behind the scenes, but the caller is responsible for releasing it.

>I just wanted to know if it used static array of char or an automatic one.
Most likely it used dynamic allocation. A static array is also possible, but an automatic array would be a ghastly error. When the function returned, an automatic array would be released, and the caller would probably get garbage.

>I guess it's wrong, right?
Yep.

>Is it a valid use?
No, it's not. Automatic variables can only be used within the scope in which they're declared. You're effectively returning the address of memory that is no longer available to you. If it works, you got incredibly unlucky. I say unlucky because it confuses you into thinking that nothing is wrong.

Yup, i had been extremely unlucky, it worked 100% of the times.

>>When the function returned, an automatic array would be released, and the caller would probably get garbage.
I think it's highly unlikely. The automatic array would be released but its very unlikely that the array contents will be changed. A simple call like cout<<func(n)-- what possibly can happen to the automatic array within such a short amount of time. I do acknowledge that it's technically a fatal error but my guess is the array contents will remain same for some short period of time. That's the reason why I think statements like cout<<func(n) worked all the time.

Ohh dont think I am trying to argue, I m just trying to give an explanation as why it had been working fine even though it's an error.

>I think it's highly unlikely.
Programmer intuition is notoriously bad. It's a common error, and people who haven't had problems with it are in the minority. For example, while it's always worked for you, it's never worked for me, and I've written programs on quite a few different compilers and systems.

>what possibly can happen to the automatic array within such a short amount of time
That's precisely the same logic that promotes this (also common, and also incorrect) code for freeing a linked list:

p = list->head;
while ( p != NULL ) {
  free ( p );
  p = p->next;
}

If it works for you, great. But it's wrong, and will burn you at the worst possible time.

>I m just trying to give an explanation as why it had been working fine even though it's an error.
In the end, it's a waste of time trying to explain undefined behavior.

does any one have an idea how to correct my code so it works? What it is suppose to do is take an integer and strip the digits and throw it in a vector and then take the sorted numbers and throw it into another vector. it then sums up the numbers and it is suppose to be quivalent to the original int.

in other words if 100 was entered then stripped and sorted it would look like
100 then would be 001 when summed would never equall 100 no matter what and the same or single digits and anything that contained a 0's.

here is the code thus far:

#include <iostream>
#include <cmath>
using namespace std;
#include "tvector.h"// equivalent to vector

int Sort_The_Digits(int n);
tvector <int> Quick(tvector<int> & sorted_list,int first,int last);
int Pivot(tvector<int> & sorted_list,int first,int last);
void Swap(int & a,int & b);
void Heading();
int main()
{
	Heading();
	tvector<int> list;
	int num;
	int sum;
	cout << "\t\tEnter A Non-Negative Number: ";//prompts user to enter a number
	cin >> num;
	
	if(num < 0)
		num *= -1;
	sum = Sort_The_Digits(num);
	cout<<"The number: "<< num<<" is equivalent to: "<< sum<<" when sorted."<<endl;


	return 0; 
}	
	
int Sort_The_Digits(int n)
{
	int value = 0;
	int index = 0;
	int product = 1;
	tvector<int> list;
	while(n > 0)
	{
		list.push_back(n%10);
		n/=10;
	}
	list = Quick(list,0,list.size()-1);
	product *= pow(10,list.size()-1);
	cout << product << endl;
	while(product >= 1)
	{
		value += list[index] * product;
		product /= 10;
		index++;
			cout << value;
	}
	return value;
}

tvector<int> Quick(tvector<int> & sorted_list,int first,int last)
// pre: a contains a.size() elements
// post: elements of a are sorted in non-decreasing order
{
	int piv;
	if(first < last)
	{
		piv = Pivot(sorted_list,first,last);
		Quick(sorted_list,first,piv-1);
		Quick(sorted_list,piv+1,last);
	}
	return sorted_list;
}

int Pivot(tvector<int> & sorted_list,int first,int last)
{
	int k,p=first;
	int pivElt = sorted_list[first];
	for(k=first+1;k<=last;k++)
	
	{
		if(sorted_list[k] <= pivElt)
		{
			p++;
			Swap(sorted_list[k],sorted_list[p]);
			
		}
	}
		Swap(sorted_list[p],sorted_list[first]);
		return p;
	
		
}

void Swap(int & a,int & b)
{
	int temp = a;
	a= b;;
	b = temp;
}


void Heading()
{
	cout << "\n\n\t\tDemonstration Of Recursion!\n\n";
}

Code tags added. You should know how to use code tags by now, so failure to use them in the future may result in disciplinary action. -Narue

>it then sums up the numbers and it is suppose to be quivalent to the original int.
I don't understand this part, especially with your example. The original int is 100, but the summed digits would be 1, not 100. Are you supposed to do some irrational magic with any zeros? Up to this point the problem is trivial, but this last requirement makes no sense. Can you be more specific?

ok what i'm trying to do is take any integer typed in by the user strip the digits, then sort it put it back into a vector and output it back out for example if you input 34 i want to output 43 after it was sorted and so on.

This is probably far from what you want, but you could save yourself a lot of trouble by using the standard library:

#include <algorithm>
#include <iostream>
#include <vector>

using namespace std;

vector<int> split ( int value )
{
  vector<int> ret;

  while ( value != 0 ) {
    ret.push_back ( value % 10 );
    value /= 10;
  }

  return ret;
}

bool compare ( const int& a, const int& b )
{
  return b < a;
}

int main()
{
  int value;

  while ( cout<<"Number: ", cin>> value ) {
    vector<int> digits = split ( value );

    sort ( digits.begin(), digits.end(), compare );
    copy ( digits.begin(), digits.end(), ostream_iterator<int> ( cout ) );
    cout<<endl;
  }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.