【问题标题】:string concatenate question in C++C ++中的字符串连接问题
【发布时间】:2011-08-23 18:56:20
【问题描述】:

我想连接一个包含路径和文件名的文件名。然后我可以打开并编写它。但我没有这样做。

char * pPath;
pPath = getenv ("MyAPP");
if (pPath!=NULL)
//printf ("The current path is: %s",pPath); // pPath = D:/temp

string str = "test.txt";
char *buf = new char[strlen(str)];
strcpy(buf,str);

fullName = ??  // how can I get D:/temp/test.txt 

ofstream outfile;
outfile.open(fullName);
outfile << "hello world" << std::endl;

outfile.close();

【问题讨论】:

  • 你到底在用char 缓冲区和strcpy 做什么?!

标签: c++ string concatenation


【解决方案1】:
char * pPath;
pPath = getenv ("MyAPP");
string spPath;
if (pPath == NULL)
  spPath = "/tmp";
else
  spPath = pPath;

string str = "test.txt";

string fullName = spPath + "/" +  str;
cout << fullName << endl;

ofstream outfile;
outfile.open(fullName.c_str());
outfile << "hello world" << std::endl;

outfile.close();

【讨论】:

    【解决方案2】:
    #include <iostream>
    #include <string>
    #include <cstdlib>
    #include <fstream>
    using namespace std;
    
    int main() {
        char* const my_app = getenv("MyAPP");
        if (!my_app) {
            cerr << "Error message" << endl;
            return EXIT_FAILURE;
        }
        string path(my_app);
        path += "/test.txt";
        ofstream out(path.c_str());
        if (!out) {
            cerr << "Error message" << endl;
            return EXIT_FAILURE;
        }
        out << "hello world";
    }
    

    【讨论】:

      【解决方案3】:
      string str = "test.txt";
      char *buf = new char[strlen(str)];
      strcpy(buf,str);
      

      应该是

      string str = "test.txt";
      char *buf = new char[str.size() + 1];
      strcpy(buf,str.c_str());
      

      但毕竟,你甚至不需要那个。 std::string 支持operator+= 的连接和char* 的构造,并公开一个返回c 样式字符串的c_str 函数:

      string str(pPath); // construction from char*
      str += "test.txt"; // concatenation with +=
      
      ofstream outfile;
      outfile.open(str.c_str());
      

      【讨论】:

      • 其实应该是new char[str.size() + 1] -- 不要忘记最后的空字节。
      • @Ernest:我不明白你的意思...... ;)
      【解决方案4】:
      string fullName = string(pPath) + "/" + ...
      
      string fullName(pPath);
      fullName += "/";
      fullName += ...;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-02
        • 2011-12-02
        • 1970-01-01
        • 2011-09-03
        相关资源
        最近更新 更多