NeverSayNever's blog

By NeverSayNever, history, 7 years ago, In English

I want to write a function that accepts one string and one integer and return concatenation of both but i always want integer to be fixed width say 3.

e.g. if string is "jamesbond" and integer is 7, function should return a string "jamesbond007". How to do it in C++ ?

Note: I dont want to write if else and other conditional statements. Thank you.

  • Vote: I like it
  • -10
  • Vote: I do not like it

»
7 years ago, # |
  Vote: I like it +5 Vote: I do not like it
string f(string s, int i)
{
	s.push_back('0'+i/100%10);
	s.push_back('0'+i/10%10);
	s.push_back('0'+i%10);
	return s;
}
  • »
    »
    7 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Yes, this is one solution but i dont want to do it since it requires a lot of code. What if the fixed width is 10 then i will be writing 10 statement. Is there any direct function in cpp that can take an integer and return a fixed width integer ?

    • »
      »
      »
      7 years ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      void concatenate(string &s, int x, int w) {

      if(w==0) return;

      concatenate(s,x/10,w-1);

      s.push_back('0'+x%10); }

    • »
      »
      »
      7 years ago, # ^ |
      Rev. 2   Vote: I like it 0 Vote: I do not like it
      string s = to_string(i);
      string t = string(max(len, s.size()) - s.size(), '0') + s;
      
»
7 years ago, # |
Rev. 4   Vote: I like it 0 Vote: I do not like it

str s2= str("i");

int l2=strlen(s2);

str dummy=("0");

make_dummy_of_length_w-l2();

return s1+dummy+s2;

»
7 years ago, # |
Rev. 2   Vote: I like it +16 Vote: I do not like it
string concat(string s, int x) {
  char tmp[s.size() + 30];
  sprintf(tmp, "%s%03d", s.c_str(), x);
  return string(tmp);
}