【问题标题】:Outputting data within a string在字符串中输出数据
【发布时间】:2013-10-10 18:25:41
【问题描述】:

在 C# 中,您可以在字符串中包含字符串或其他数据。例如:

string myString = "Jake likes to eat {0}", food  

Console.WriteLine("Jake likes to eat {0}", food);

如何在 C++ 中做到这一点?对于我正在编写的程序,我的代码显示:

getline(cin, obj_name);
property_names[j].Set_Type("vector<{0}>", obj_name);

如何将 obj_name 值放在大括号内?

【问题讨论】:

标签: c++ string


【解决方案1】:

如果您的 obj_name 是 std::string,您可以按照 nhgrif 的建议进行操作

"vector<{" + obj_name + "}>"

如果您的 obj_name 是 char [],则可以使用与 printf 具有相似行为的 sprintf

int sprintf ( char * str, const char * format, ... );

【讨论】:

    【解决方案2】:

    你可以使用 c: 中的 sprintf()

    char buf[1000];
    sprintf(buf, "vector<%s>", obj_name);
    

    【讨论】:

      【解决方案3】:

      如果你想念 C++ 中的 sprintf 并且想使用更多 C++ 风格的东西,请尝试使用 Boost 中的格式。

      #include <iostream>
      #include <boost/format.hpp>
      
      using namespace std;
      using boost::format;
      
      int main()
      {
          string some_string("some string"),
                 formated_string(str(format("%1%") % some_string));
      
          cout << formated_string << endl;
      
          return 0;
      }
      

      【讨论】:

        【解决方案4】:

        您可以从 c# 中创建一个几乎类似于 WriteLine 的函数:

        void WriteLine(string const &outstr, ...) {
            va_list placeholder;
            va_start(placeholder, outstr);
            bool found = false;
            for (string::const_iterator it = outstr.begin(); it != outstr.end(); ++it) {
                switch(*it) {
                    case '{':
                        found = true;
                        continue;
                    case '}':
                        found = false;
                        continue;
                    default:
                        if (found) printf("%s", va_arg(placeholder, char *));
                        else putchar(*it);
                }
            }
            putchar('\n');
            va_end(placeholder);
        }
        

        用类似的论点来称呼它:

        WriteLine("My fav place in the world is {0}, and it has a lot of {1} in it", "Russia", "Mountains");
        

        输出:

        My fav place in the world is Russia, and it has a lot of Mountains in it
        

        该函数当然不是完美的,因为 c# 中的 System.Console.WriteLine() 函数可以使争论不按顺序排列,但仍将正确的字符串放置在完整字符串中的正确位置。这可以通过首先将所有参数放在一个数组中并访问数组的索引来解决

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-08-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-05-31
          • 2017-02-09
          • 2014-11-07
          相关资源
          最近更新 更多