c++ - 我如何编写类字符串的重载运算符>>函数?

标签 c++

class string 
{ 
  public: 
        friend istream& operator >> ( istream& is, string& str); 
  private: 
        char *m_data; 
}; 

int main() 
{ 
  string str; 
  freopen("in.txt","r",stdin); 
  while( cin >> str) 
  { 
      cout < < str < < endl; 
  } 
  return 0; 
}

in.txt的内容是:

asdfsfgfdgdfg

在重载函数中,我使用is.get()一个一个读取这些字符,但是当cin完成时程序跳出圆圈,这意味着cout不会运行。另一方面,我尝试用getchar()代替,但是跳不出圈。

问题:我对这个功能的想法有什么问题吗?或者有另一种更好的方式来实现。谢谢:)

============================================= ========================================== 新编辑: 这是我的代码: @Artem巴格 代码详情

#include <iostream>

namespace Str

{
    class string
    {
    public:
        string():k(0){}

    friend bool operator >> ( std::istream& is, string& str)
    {
        int size = 100;
        char m;

        if( (m = getchar()) && m == -1)
            return false;

        str.m_data = new char[size];

        do
        {
            if( str.k == size)
            {
                size *= 2;
                char *temp = new char[size];
                for( int j = 0; j < str.k; ++j)
                {
                    char *del = str.m_data;
                    temp[j] = *str.m_data++;
                    delete del;
                }
                str.m_data = temp;
                temp = NULL;
            }

            str.m_data[str.k++] = m;
        }while( (m = getchar()) && m != -1);

        return true;
    }

    friend void operator << ( std::ostream& os, string& str)
    {
        os << str.m_data;
        str.k = 0;
        delete []str.m_data;
    }

private:
    char *m_data;
    int k;
};
}


using namespace Str;
int main()
{

string str;

while( std::cin >> str)
{
    std::cout << str;
}

return 0;
}

内容还是有问题

do
{
}while();

最佳答案

也许您可以像这样重写您的代码,这应该可以解决您的问题:

bool success = true;

while (sucess) {
  success = cin >> str;
  cout << str;
}

但是,我不明白为什么你仍然希望 cout 继续 - 如果 cin 调用没有成功,你只会打印旧的字符串的内容 - 你不能在任何地方清除它(除非你在你没有在这里发布的其他代码中这样做)。

关于c++ - 我如何编写类字符串的重载运算符>>函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1037744/

相关文章:

c++ - 模板类中重载函数的条件编译

c++ - 使用相同的 Boost.Asio io_service 同步接受 tcp 连接并作为线程池

c++ - 调用父类(super class)构造函数的规则是什么?

c++ - 在 C++ 中,枚举数据类型占用多少内存?

c++ - 我可以从函数返回 printf 语句吗? C++

c++ - 使用流读取文件

c++ - std::async 在 Visual Studio 2013 和 2015 之间的不同行为

c++ - 使用 Boost,如何将自定义边缘属性作为结构放置/获取?

c++ - 为什么我换的木屐不粘?

c++ - 在 C++ 中内存具有两个输入的函数