C++ 串接字符串和数字

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

我试图读取一些图像并将信息复制到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);
 }
}
文件*ident;

对于(k=0;k您可以使用
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;
}

一个好方法是使用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);
  }
}
#包括
#包括
文件*标识;
常量std::字符串前缀(“pt_176118_x_”);
常量std::字符串后缀(“_cand_test.pgm”);

对于(k=0;您尝试使用的kdid to_string()函数?为什么不简单地
sprintf(突出“pt_176118_x%d_cand_test.pgm”,num)
?对于这个变体,我得到了错误:访问冲突写入位置我正在使用Microsoft Visual Studio 2008,当我尝试编译程序时,它给了我这个错误:错误C3861:“to_字符串”:找不到标识符。我应该提到的是,我还包括了那些库std::to_字符串是在c++11中引入的,不会是我n VS2008很遗憾。是的,您可能想在问题中提到这一点。无论如何,我已经更新了我的答案,添加了一个C++98示例(不使用std::to_string())。
#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);
  }
}