【问题标题】:concatenate strings and numbers连接字符串和数字
【发布时间】:2014-05-21 15:10:44
【问题描述】:

我正在尝试读取一些图像并将信息复制到 3D 缓冲区(矩阵缓冲区,其中每个矩阵中的信息是来自图像的信息)。要使用 fopen 打开图像,我需要图像的名称(例如“pt_176118_x_0600_cand.pgm”)。对于读取多个文件,数字 0600(开始 = 600)将增加一个步长 = 5 直到达到 02400。所以我需要连接“pt_176118_x_”、一个数字和“_cand.pgm”。我的问题是如何做到这一点,更准确地说,如何将数字转换为字符串,然后,如何转换或表示该字符串以便 fopen 可以识别它

虽然我在这里搜索过合适的解决方案,但似乎没有一个适合这种情况。 我的代码是:

FILE *ident;

for(k=0;k<360;k++)
         {     printf("\r Read slice: %d (real: %d)",k,start + step*k);
               num = start+step*k;
               sprintf(outString,"%s%d%s","pt_176118_x_%d",num,"_cand_test.pgm");

               if( ( ident = fopen(outString,"rb")) == NULL)
                {
               printf(" Error opening file %s \n",outString);
                   exit(1);
 }
}

【问题讨论】:

  • 您是否尝试过使用 to_string() 函数?
  • 为什么不简单地sprintf(outString,"pt_176118_x_%d_cand_test.pgm",num);??
  • 对于这个变种我得到错误:访问冲突写入位置

标签: c++ string-concatenation


【解决方案1】:

您可以使用std::string 构建字符串,并使用std::to_string() 将整数转换为字符串。

请注意,fopen() 需要一个原始 C 字符串指针:因此,给定 std::string,您可以调用其 c_str() 方法并将其返回值传递给 fopen()

用于构建文件名的示例可编译代码如下:

#include <iostream>
#include <string>
using namespace std;

int main() {
    int num = 600;
    string filename = "pt_176118_x_0";
    filename += to_string(num);
    filename += "_cand.pgm";

    cout << filename << endl;
}

编辑

在评论中,OP 指出他正在使用 VS2008 C++ 编译器,它不支持 C++11 的 std::to_string()

在这种情况下,std::ostringstream 可以用作纯 C++ 替代方案(或者也可以使用 C 的 sprintf()itoa()):

#include <iostream>
#include <sstream>
#include <string>
using namespace std;

string BuildFilename(int num) {
    ostringstream os;
    os << "pt_176118_x_0" << num << "_cand.pgm";
    return os.str();
}

int main() {
    int num = 600;    
    cout << BuildFilename(num) << endl;
}

【讨论】:

  • 我正在使用 Microsoft Visual Studio 2008,当我尝试编译程序时,它给了我这个错误:error C3861: 'to_string': identifier not found 。我应该提到我还包括了这些库
  • std::to_string 是由 c++11 引入的,遗憾的是不会出现在 VS2008 中。
  • 是的,您可能想在问题中提及这一点。无论如何,我已经更新了我的答案,添加了一个 C++98 示例(不使用 std::to_string())。
【解决方案2】:

一个好办法是使用std::stringstream

#include <sstream>
#include <string>
FILE *ident;
const std::string prefix ("pt_176118_x_");
const std::string postfix ("_cand_test.pgm");

for(k=0;k<360;k++) {
  printf("\r Read slice: %d (real: %d)",k,start + step*k);
               num = start+step*k;

  std::stringstream outString;
  outString << prefix  <<  num << postfix; 
  const char* file_name = outString.Str ().c_str ()


  if( ( ident = fopen(file_name,"rb")) == NULL) {
               printf(" Error opening file %s \n",outString.Str ().c_str);
                   exit(1);
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-30
    • 1970-01-01
    • 2023-03-27
    • 2013-12-29
    • 2021-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多