【问题标题】:Getline in class c++C++ 类中的 Getline
【发布时间】:2014-04-17 22:46:29
【问题描述】:

我正在尝试编写一个 getline 函数,该函数将从开放流中接收一串单词...我查看了不同的网站并尝试了它所说的操作,但我遇到了很多奇怪的错误。我需要 getline 来接收文件“内容”部分中的所有单词。这是我尝试过的,但我遇到了错误。

// Fill a single Tweet from a stream (open file)
// Returns true if able to read a tweet; false if end of file is encountered
// Assumes that each line in the file is correct (no partial tweets)
bool Tweet::FillTweet(ifstream &Din)
{
   string tmp;

   bool Success = false;
   Din >> tmp;
   if (!Din.eof())
   {
      Success = true;
      date = tmp;
      Din >> hashtag >> getline(Din,contents);
   }
   else
      cout << "I don't want to read your tweet anyway. " << endl;

【问题讨论】:

    标签: c++ class methods getline


    【解决方案1】:

    这是使用getline() 的错误方式。改为:

    Din >> hashtag;
    getline(Din,contents);
    

    为什么? getline() 返回对 istream 的引用。没有重载的&gt;&gt; 运算符需要两个istreams

    【讨论】:

      【解决方案2】:

      这个

        Din >> hashtag >> getline(Din,contents);
      

      需要:

        Din >> hashtag;
        getline(Din, contents);
      

      我也会这样做

      if (Din >> tmp)
      

      而不是if (!Din.eof)

      【讨论】:

      • 你能解释一下为什么你会改变 if(!Din.eof) 吗?
      • 因为您避免了额外的检查 - 如果无法读取 date 但它不是 EOF,您将不会获得无限循环。 (当然,字符串不太可能)
      • Because of this。检查你的 io 而不是假设它们是正确的总是是个好主意。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多