【问题标题】:C++ stringstream returning extra character?C++ stringstream 返回额外的字符?
【发布时间】:2010-12-05 04:55:10
【问题描述】:

我一直在尝试使用 C++ stringstream 类来做一些相对简单的字符串操作,但是我遇到了 get() 方法的问题。出于某种原因,每当我逐个字符提取输出时,它都会附加最后一个字母的第二个副本。

#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main() {
   stringstream ss("hello");
   char c;

   while(!ss.eof()) {
      ss.get(c);
      cout << "char: " << c << endl;
   }
   return 0;
}

程序的输出是:

char: h
char: e
char: l
char: l
char: o
char: o

如果您能在这方面给我任何帮助,我们将不胜感激。

【问题讨论】:

  • 是的,这是一个错字。 #include 应该是 #include

标签: c++ string stream sstream


【解决方案1】:

在流的末尾ss.eof() 还不知道即将到达流的末尾,但是以下字符的提取失败。由于到达流的末尾而导致提取失败,c 不会更改。您的程序无法识别 ss.get(c) 失败并再次打印 c 的旧值。

检查是否还有可以从流中读取的字符的更好方法是这样的循环:

while (ss.get(c)) {
   cout << "char: " << c << endl;
}

【讨论】:

  • 在这里,您依赖于定义了 operator bool() 的标准流的便利性。
  • 非常感谢您的快速回复和详细解释。
【解决方案2】:

这是因为循环的顺序。您正在阅读 \0 和 EOF。

像这样重新排列你的代码

int main() {
   stringstream ss("hello");
   char c;

   ss.get(c);
   while(!ss.eof()) {
      cout << "char: " << c << endl;
      ss.get(c);
   }
   return 0;
}

【讨论】:

    【解决方案3】:

    仅当您尝试读取文件末尾的 PAST 时才会设置 EOF 标志。以下代码通过在 get() 之后而不是之前测试 EOF 来解决问题:

    #include <iostream>
    #include <sstream>
    #include <string>
    using namespace std;
    
    int main() {
       stringstream ss("hello");
       char c;
    
       while(1) {
          ss.get(c);
          if(ss.eof())
              break;
    
          cout << "char: " << c << endl;
       }
       return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 2019-09-19
      • 1970-01-01
      • 1970-01-01
      • 2016-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多