【问题标题】:Trying to concatenate strings with <<尝试用 << 连接字符串
【发布时间】:2015-01-29 17:03:28
【问题描述】:

我学习java编程已经半年了,现在我也在努力学习c++。

我正在使用 minGW 和代码块。我的问题是我试图将文件从一个路径复制到另一个路径。这很好用:

system("copy c:\\test.txt c:\\test2.txt");

但是当我尝试这个时它不起作用(currPath 和 dest 是字符串)

system("copy " << currPath << " " << "c:\\" << dest << "\\hej.exe" << end1);

我收到了错误:

error: no match for 'operator<<' in '"copy " << currPath'

字符串 currpath 和 dest 只包含一个 \,但我认为这不是问题。

【问题讨论】:

  • 我想知道谁对这个问题投了反对票,他这样做的原因是什么。也许这不是有史以来最好的答案,但对 SO 有效。

标签: c++ string stdstring


【解决方案1】:

您尝试使用的operator&lt;&lt; 与C++ 流相关联。您当前没有使用流,因此您应该使用 operator+std::string 连接字符串:

auto str = std::string("copy ") + currPath + " c:\\" + dest + "\\hej.exe\n";
system(str.c_str());

或者,使用C++14 literals

auto str = "copy "s + currPath + " c:\\" + dest + "\\hej.exe\n";

【讨论】:

  • 附录:注意临时字符串在表达式末尾被破坏。并不是说它在这里有任何影响。
  • 我是否必须插入一个额外的反斜杠,因为在字符串中文件夹之间只有一个反斜杠?我想如果它将反斜杠解释为转义字符?
  • @Johan "c:\\"be interpreted 变成"c:\"
  • @Jefffrey 谢谢,有一段时间被所有的斜线弄糊涂了,但现在一切正常。到那时也无法对您的答案进行投票,所以现在就这样做了,非常感谢:)
  • 我认为
【解决方案2】:

如果你想使用operator&lt;&lt;把字符串放在一起,你需要使用std::ostringstream

std::ostringstream strm;
strm << "copy " << currPath << " " << "c:\\" << dest << "\\hej.exe";
system(strm.str().c_str());

它可以被包装,因为它不需要持续超过这一行:

system((std::ostringstream{} << "copy " << currPath << " " 
             << "c:\\" << dest << "\\hej.exe").str().c_str());

但这对眼睛来说有点难。

【讨论】:

    猜你喜欢
    • 2021-04-26
    • 1970-01-01
    • 2022-06-17
    • 2021-07-04
    • 1970-01-01
    • 1970-01-01
    • 2012-08-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多