• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 194
  • Last Modified:

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"
0
ruffone
Asked:
ruffone
3 Solutions
 
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
 
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

Featured Post

The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now