Trying to learn C++

How so I write a function that takes an integer "78913452" and returns a string like this "7  8  9  1  3  4  5  2"
LVL 4
ruffoneAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

jkrCommented:
Well, basically you iterate through the string and copy each element to a new one by adding space, e.g.

#include <string>
#include <iostream>
using namespace std;
 
string add_spaces(const string& in) {
 
  string out;
  size_t len = in.length();
  
  for (size_t i = 0; i < len; ++i) {
 
    out += in[i];
    out += ' ';
  }
 
  return out;
}
 
int main () {
 
  string in = "78913452";
  string out = add_spaces(in);
 
  cout << in << endl;
 
  cout << out << endl;
 
  return 0;
}

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
evilrixSenior Software Engineer (Avast)Commented:
>> How so I write a function that takes an integer "78913452" and returns a string like this "7  8  9  1  3  4  5  2"
To convert an integer to a string so that jkr's solution will work...

#include <sstream>
 
int main()
{
	int num = 78913452;
	std::stringstream ss;
 
	ss << num;
 
	std::string const & in = ss.str();
 
	// Call jkr's code goes here
	string out = add_spaces(in);
 
	return 0;
}

Open in new window

0
IchijoCommented:
This way doesn't add an extra space at the end:
#include <sstream>
#include <string>
 
using namespace std;
 
string integer_to_string_with_spaces(int n)
{
    stringstream buf;
    buf << n;
    string s = buf.str();
 
    for( string::iterator it = s.begin() + 1; it != s.end(); ++it, ++it )
    {
        s.insert( it, ' ' );
    }
 
    return s;
}
 
int main()
{
    int n = 78913452;
    string s = integer_to_string_with_spaces(n);
 
    cout << s << endl;
 
    return 0;
}

Open in new window

0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C++

From novice to tech pro — start learning today.