Read integer to a string?

How do I read integers to a string and store then into a vector array?

I need to add two input digits i.e. "1234567878887777" and "123344543543543"

Simply input them into string variable rather than into integer one.


add two input digits

I fear I did not understand.
Last edited on
Integer To String (I use string format instructions)

Narrow:
1
2
3
4
5
6
7
8
9
10
11
12
//ANSI (non-unicode)
char *fmt = new char[260];
int IntValue = 1337;
unsigned long UnsignedIntValue = 7887;
float FloatValue = 13.37;
double DoubleValue = 999.333;

sprintf(fmt, "Integer value (signed): %i; Integer value (unsigned): %ul; Float value: %.2f; Double Value: %.2f", IntValue, UnsignedIntValue, FloatValue, DoubleValue);

OutputDebugStringA(fmt);
//or (for debugging purposes)
MessageBoxA(0, fmt, fmt, 0);


Wide:
1
2
3
4
5
6
7
8
9
10
11
12
//Unicode
wchar_t *fmt = new wchar_t[260];
int IntValue = 1337;
unsigned long UnsignedIntValue = 7887;
float FloatValue = 13.37;
double DoubleValue = 999.333;

swprintf(fmt, L"Integer value (signed): %i; Integer value (unsigned): %ul; Float value: %.2f; Double Value: %.2f", IntValue, UnsignedIntValue, FloatValue, DoubleValue);

OutputDebugStringW(fmt);
//or
MessageBoxW(0, fmt, fmt, 0);



And obviously to go the other way is it a little trickier but very do able...

1
2
3
4
5
6
7
8
9
10
11
12
13
char *intAsString = "0x1415";
char *floatingPointAsString = "2384.414";
wchar_t *intAsString2 = "43204";
wchar_t *floatingPointAsString2 = "9423.93";

long ConvertedFromString = strtol("50971", 0, 10);
unsigned long ConvertedFromString2 = strtol(intAsString, 0, 16);
unsigned long ConvertedFromUniString = wcstol(L"0x539", 0, 16);
long ConvertedFromUniString2 = wcstol(intAsString2, 0, 10);


double DoubleFromStringOne = strtod(floatingPointAsString, 0);
double DoubleFromStringTwo = wcstod(floatingPointAsString2, 0); 


I need to add two very long integers, but I need to have them read from a long integer to a string then into a vector array and reversed to be added together to get a sum since very long numbers will give you a 4^1000 ect....
> since very long numbers will give you a 4^1000 ect....

4^1000 would be outside the range of the largest standard integer type.
Use a library which has a large precision integer type.

For instance, Boost.Multiprecision
http://www.boost.org/doc/libs/1_54_0/libs/multiprecision/doc/html/index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <boost/multiprecision/cpp_int.hpp>
#include <string>
#include <iostream>
#include <iomanip>

using int_t = boost::multiprecision::cpp_int ;

int_t reverse( const int_t& n )
{
    if( n < 0 ) return - reverse( -n ) ;
    else if( n < 10 ) return n ;
    else
    {
        std::string str = n.str() ;
        auto pos = str.find_last_not_of('0') ;
        if( pos != str.size() - 1 ) str = str.substr( 0, pos+1 ) ;
        return int_t( std::string( str.rbegin(), str.rend() ) ) ;
    }
}

int main()
{
    constexpr int width = 40 ;
    const auto setw = std::setw(width) ;

    const int_t i { "123456789012345678901234567890" } ;
    const int_t j = reverse(i) ;
    std::cout << setw << i << '\n' << setw << j << "\n\n" ;

    const int_t k = 111333555777999 ;

    std::cout << setw << j << " +\n"
               << setw << k << '\n'
               << std::string( width, '-' ) << '\n'
               << setw << j + k << '\n' ;
}

http://coliru.stacked-crooked.com/a/dcce8de580e1e5a3
I have to use vectors, I've already got two inputs into two vectors, now I need to add both of those vector and pushback it to a third vector to hold the sum of those two vectors, how do I add them and take care of the carry over number?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
here's what I got so far,

                              vector<int> vecNum;
		vector<int> vecNum2;
		string num1; 
		string num2 ; 
		char num1Temp;
		string realNum;

		cout << "\nEnter a large number." << endl; 
		/*cin >> num1; */
		std::getline (std::cin,num1);
		//for( const auto &it : num1 )
		//vecNum.push_back( *it );
		for(int i=0; i<num1.length(); i++)      
       {      
          if(isdigit(num1[i]))      
		  vecNum.push_back( num1[i]-'0' ); 
       } 

	//for(int i=0; i< vecNum.size();i++)
	//{
	//	cout << vecNum[i];
	//}
	cout << endl;
	for (int i=vecNum.size()-1; i>=0; i--) {   
        cout << vecNum[i];            
    }
		cout << "\nEnter a second large number." << endl; 
		/*cin >> num2; */
		std::getline (std::cin,num2);
		for(int i=0; i<num2.length(); i++)      
       {      
          if(isdigit(num2[i]))      
		  vecNum2.push_back( num2[i]-'0' ); 
       } 
		cout << endl;
		for (int i=vecNum2.size()-1; i>=0; i--) {   
        cout << vecNum2[i];          
    } 
Last edited on
> I have to use vectors

std::deque<> would have been more convenient.


> how do I add them and take care of the carry over number?

This is one way:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <iostream>
#include <vector>
#include <algorithm>

int main()
{
    const auto print = []( const std::vector<int>& seq )
    {
        for( std::size_t i = 40 ; i > seq.size() ; --i ) std::cout << ' ' ;
        for( int digit : seq ) std::cout << digit ;
        std::cout << '\n' ;
    };

    const std::vector<int> a { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0,
                               1, 2, 3, 4, 5, 6, 7, 8, 9, 0,
                               1, 2, 3, 4, 5, 6, 7, 8, 9, 0 } ;
    print(a) ;

    const std::vector<int> b( a.size()/2, 9) ;
    print(b) ;

    // a + b

    // step 1. make reverse of a and b
    std::vector<int> rev_a( a.rbegin(), a.rend() ) ;
    std::vector<int> rev_b( b.rbegin(), b.rend() ) ;

    // step 2. make them of the same size by adding zeroes at the end
    const std::size_t sz = std::max( a.size(), b.size() ) ;
    rev_a.resize(sz) ;
    rev_b.resize(sz) ;

    std::vector<int> result ;

    // step 3. add digit by digit with carry and push back into result
    int carry = 0 ;
    for( std::size_t i = 0 ; i < sz ; ++i )
    {
        const int sum = rev_a[i] + rev_b[i] + carry ;
        carry = sum / 10 ;
        result.push_back( sum % 10 ) ;
    }
    while( carry > 0 ) { result.push_back( carry%10 ) ; carry /= 10 ; }

    // step 4. reverse the result to get the answer
    std::reverse( result.begin(), result.end() ) ;

    print(result) ;
}

http://coliru.stacked-crooked.com/a/711fd99f472b1e71

std::deque<> has an efficient push_front(); with it the reverse - add with carry and push_back - reverse the result would not be needed.
What in this code do I need to replace to get my codes to work, I have my two inputs as strings and into vectors already, the code itself is getting me errors, here's one of them,

const std::vector<int> a { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0,
1, 2, 3, 4, 5, 6, 7, 8, 9, 0,
1, 2, 3, 4, 5, 6, 7, 8, 9, 0 } ;

<< needs a ; before the first squiggle bracket.
> What in this code do I need to replace to get my codes to work

What is the point in somehow getting this code to compile cleanly with your compiler, if you do not understand what it does?


> I have my two inputs as strings and into vectors already, the code itself is getting me errors

First, try to understand the logic of adding two numbers digit by digit with carry. The code above illustrates one specific way of doing it; the basic idea would be the same everywhere - add digit by digit starting with the least significant digit, keeping track of the carry into the next more significant digit.

Once you have got that logic clear in your mind, implement it in your own code, using language constructs that you are already familiar with.

After you have done that much, you might want to know more about the things in code that you saw for the first time; you could post follow up questions about those.
Topic archived. No new replies allowed.