【问题标题】:Detect when at the end of a stringstream检测何时在字符串流的末尾
【发布时间】:2013-12-13 17:13:45
【问题描述】:

我正在尝试编写一个函数,该函数将检测我何时接近字符串流的末尾,但它似乎不起作用。

这里有一些代码:

std::string path(1.2.3);
int number;
std::stringstream ss(path);
while (!ss.eof()) {
    if (ss.peek() != '.') {
        ss >> number;
        if (ss.tellg() == path.length()) {
            std::cout << "Last one: " << number;
        } else {
            std::cout << number;
        }
    } else { ss.get(); }
}

我尝试使用 ss.tellg() == path.length(),但这不起作用。有人有替代品吗?

【问题讨论】:

  • @Dave 那也不行。

标签: c++ string stringstream


【解决方案1】:

我想通了..

std::string path(1.2.3);
int number;
std::stringstream ss(path);
while (!ss.eof()) {
    if (ss.peek() != '.') {
        ss >> number;
        if (ss.tellg() == -1) {
            std::cout << "Last one: " << number;
        } else {
            std::cout << number;
        }
    } else { ss.get(); }
}

【讨论】:

  • 嗯...您从未将值提取到number,那么您为什么要尝试打印它?
  • 最好直接做while (ss)。 EOF 只是您无法再从流中读取的几个原因之一。
  • @EduardoLeón 是对的。当ss 为假时,表示您无法再阅读。然后打电话给ss.eof(),告诉end of file是否是你无法阅读的原因。
  • 在不了解它们可以返回什么的情况下,不应使用任何建议的终止条件。 @pyon 使用 while(ss) 将导致在退出时读取额外的虚假值。 @JNevens ss.eof() 可以为 0 的原因有很多,所以我们不能确定预期的终止是循环退出的原因;一些讨论here
  • while (ss.peek() != EOF) 怎么样
猜你喜欢
  • 1970-01-01
  • 2013-11-12
  • 2014-03-11
  • 1970-01-01
  • 1970-01-01
  • 2011-04-01
  • 1970-01-01
  • 2014-11-22
  • 1970-01-01
相关资源
最近更新 更多