Пожалуйста, прочтите новое правило об ограничении использования AI-инструментов. ×

Блог пользователя NeverSayNever

Автор NeverSayNever, история, 8 лет назад, По-английски

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.

  • Проголосовать: нравится
  • -10
  • Проголосовать: не нравится

»
8 лет назад, # |
  Проголосовать: нравится +5 Проголосовать: не нравится
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;
}
  • »
    »
    8 лет назад, # ^ |
      Проголосовать: нравится 0 Проголосовать: не нравится

    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 ?

    • »
      »
      »
      8 лет назад, # ^ |
        Проголосовать: нравится 0 Проголосовать: не нравится

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

      if(w==0) return;

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

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

    • »
      »
      »
      8 лет назад, # ^ |
      Rev. 2   Проголосовать: нравится 0 Проголосовать: не нравится
      string s = to_string(i);
      string t = string(max(len, s.size()) - s.size(), '0') + s;
      
»
8 лет назад, # |
  Проголосовать: нравится +21 Проголосовать: не нравится
#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
using namespace std;

string f(string const& s, int d) {
	stringstream ss;
	ss << s << setw(3) << setfill('0') << d;
	return ss.str();
}

int main() {
	cout << f("jamesbond", 7);
}
»
8 лет назад, # |
Rev. 4   Проголосовать: нравится 0 Проголосовать: не нравится

str s2= str("i");

int l2=strlen(s2);

str dummy=("0");

make_dummy_of_length_w-l2();

return s1+dummy+s2;

»
8 лет назад, # |
Rev. 2   Проголосовать: нравится +16 Проголосовать: не нравится
string concat(string s, int x) {
  char tmp[s.size() + 30];
  sprintf(tmp, "%s%03d", s.c_str(), x);
  return string(tmp);
}