获取输出并将其存储到变量中

Taking output and storing it into a variable?

本文关键字:变量 存储 输出 获取      更新时间:2023-10-16

我有这个代码:

string text;
getline(cin ,text);
istringstream iss(text);
copy(
    istream_iterator<string>(iss),
    istream_iterator<string>(),
    ostream_iterator<string>(cout,"n")
);

当我输入一个字符串时:bf "inging" filename,它输出:

bf
"inging"
filename

有没有办法让我获取每个单独的输出并将其保存到变量中?

当然可以捕获不同的输出并对其进行处理:您将创建一个流缓冲区来检测换行符并对自上次换行符以来收到的字符执行某些操作。只有这样,您才会将字符串转发到其他地方。虽然可行,但我怀疑这真的是你想做的。

如果你想从流中捕获所有std::string,并且你不希望每个都有一个特定的名称,例如,因为你不知道需要多少个字符串,你可以将它们存储到std::vector<std::string>中使用

std::vector<std::string> strings{ std::istream_iterator<std::string>(iss),
                                  std::istream_iterator<std::string>() };

。或

std::vector<std::string> strings;
std::copy(std::istream_iterator<std::string>(iss),
          std::istream_iterator<std::string>(),
          std::back_inserter(strings));

如果你想让字符串在单个变量中,你只需将它们读入变量并确保你读取所有变量:

std::string a, b, c;
if (iss >> a >> b >> c) {
    std::cout << "read a='" << a << "' b='" << b << " c='" << c << "'n";
}
else {
    std::cout << "failed to read three strings from line '" << text << "'n";
}