来自矢量的 C++ 字符串串联

c++ string concatenation from vector

本文关键字:字符串 C++      更新时间:2023-10-16

我使用以下代码:

std::string exec(const char* cmd) {
std::array<char, 128> buffer;
std::string result;
std::shared_ptr<FILE> pipe(_popen(cmd, "r"), _pclose);
if (!pipe) throw std::runtime_error("popen() failed!");
while (!feof(pipe.get())) {
if (fgets(buffer.data(), 128, pipe.get()) != nullptr)
result += buffer.data();
}
return result;
}
std::vector<std::string> split(const std::string &s, char delim) {
std::vector<std::string> elems;
split(s, delim, std::back_inserter(elems));
return elems;
}

当我想要从行数组和"hello"连接字符串时

std::vector<std::string> lines = split(exec("wmic path win32_baseboard get SerialNumber"), 'n');
std::ostringstream stringStream;
stringStream << lines[1];
stringStream << "hello";
std::cout << stringStream.str() << endl;

然后我得到了像在这里
输入图像描述这样的输出 所以单词"hello"插入开始,并替换我的序列号输出 但输出
必须是"%序列号%hello">
我做错了什么? :)

正如 tkausl 所提到的,在 Windows 中,字符串的末尾是 CR LF 符号 (\r( 的组合,而不是简单的 Linux 风格的 LF ((。

请参阅控制台输出示例。