【问题标题】:Concatenating an integer to a string [duplicate]将整数连接到字符串[重复]
【发布时间】:2013-02-26 14:12:53
【问题描述】:

我正在尝试在 Visual Studio 2008 中保存一系列图像,所有图像都带有“图像”前缀。 唯一的区别因素应该是它们的数量。 例如,如果我要保存 10 张图像,那么情况应该是

i=1;
while(i<10)
{
cvSaveImage("G:/OpenCV/Results/Imagei.jpg",img2);
i++
//"i" is gonna be different every time
}

所以我需要将整数与字符串连接起来...... 期待答案...

【问题讨论】:

  • 您的问题不是关于保存一系列图像,而是关于字符串操作。
  • 字符名称[50]; sprintf(name,"文件名%d.jpg", 10); // 还要检查 snprintf 以打印最多 50 个字符。
  • @AkiSuihkonen,这不是 C++ 方式,但将其作为答案发布,以便解决问题。
  • @AkiSuihkonen,这可行,但 cvSaveImage 似乎没有将数组作为保存图像的路径:(

标签: c++


【解决方案1】:

c++ 方式(c++11 之前)是:

#include <sstream>
...
ostringstream convert;
convert << "G:/OpenCV/Results/Image" << i << ".jpg";
cvSaveImage(convert.str().c_str(), img2);
i++;

【讨论】:

    【解决方案2】:

    使用 C++11:

    #include <string>
    
    string filename = "G:/OpenCV/Results/Image" + to_string(i) + ".jpg";
    cvSaveImage(filename.c_str(), img2);
    

    编辑

    构建字符串的一种通用且可能更有效的方法是使用stringstream

    ostringstream ss;
    
    ss << "G:/OpenCV/Results/Image" << i << ".jpg";
    
    string filename = ss.str();
    cvSaveImage(filename.c_str(), img2);
    

    这也适用于 C++11 之前的编译器。

    【讨论】:

      【解决方案3】:

      首先,如果您以i = 10 开头并执行while( i &lt; 10 ),那么您的代码将只保存9 个项目。现在回答你的问题,

      for( i = 1; i < 11; i++ )
      {
        std::stringstream imagenum;
        imagenum << "G:/OpenCV/Results/Image" << i << ".jpg" ;
        cvSaveImage(imagenum.str().c_str(), img2) ;
      }
      

      查看example_link

      【讨论】:

        【解决方案4】:

        opencv 带有 cv::format() [这可能只是一个 sprintf 包装器,但非常方便,恕我直言]

        所以,您的示例可能如下所示:

        cv::imwrite( cv::format( "G:/OpenCV/Results/Image%d.jpg", i ), img );
        

        或者,如果你坚持使用过时的 1.0 api,:

        cvSaveImage( cv::format( "G:/OpenCV/Results/Image%d.jpg", i ).c_str(), img );
        

        【讨论】:

          【解决方案5】:
          string imgname="./Image_";
          char cbuff[20];
          sprintf (cbuff, "%03d", i);
          imgname.append(cbuff);
          imgname.append(".jpg");
          

          输出:

          ./Image_001.jpg
          ./Image_002.jpg
          ./Image_010.jpg etc.
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2017-05-11
            • 2011-02-20
            • 1970-01-01
            • 1970-01-01
            • 2019-01-05
            • 2017-06-21
            • 1970-01-01
            相关资源
            最近更新 更多