【问题标题】:Taking output and storing it into a variable?获取输出并将其存储到变量中?
【发布时间】:2013-09-08 16:44:27
【问题描述】:

我有这个代码:

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

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

【问题讨论】:

    标签: c++ variables iterator output getline


    【解决方案1】:

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

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

    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";
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-18
      • 1970-01-01
      • 1970-01-01
      • 2016-10-19
      • 2013-01-25
      • 1970-01-01
      相关资源
      最近更新 更多