连接字符串和数字

时间:2014-05-21 15:10:45

标签: c++ string-concatenation

我正在尝试读取一些图像并将信息复制到3D缓冲区(矩阵缓冲区,其中每个矩阵中的信息是图像中的信息)。要使用fopen打开图像,我需要图像的名称(例如,#34; 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);
 }
}

2 个答案:

答案 0 :(得分:0)

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

请注意,fopen()需要一个原始C字符串指针:因此,在std::string的情况下,您可以调用其c_str()方法并将其返回值传递给fopen()。< / p>

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

#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 ++ comepiler,它不支持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;
}

答案 1 :(得分:0)

一个好方法是使用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);
  }
}