C++ - how would I do this?

Discussion in 'Computer Programming, Emulation, and Game Modding' started by Nyap, Jul 20, 2016.

  1. Nyap
    OP

    Nyap HTML Noob

    Banned
    973
    344
    Jan 13, 2016
    That Chaos Site
    so I know what my problem is I just don't know how to fix it
    I want to avoid using std::string although I know that would fix my problem easily.
    Code:
    protected:
      //Checks if string is dynamically allocated
       bool isDynamic{};
       //Size of the string
      int bufferSize{};
      //Pointer to the string
      char* Buffer;
    
    //Extract a line from an ifstream
    void getline(ifstream& input)
    {
      char oneBuffer;
      bufferSize=0;
      for (int i{}; oneBuffer!='\n' && input; ++i, ++bufferSize)
            input >> oneBuffer;
      Buffer=new char[bufferSize];
      input.close();
      input.open("lol.txt");
      for (int i{}; i<=bufferSize; ++i)
      {
             input >> oneBuffer;
             Buffer[i]=oneBuffer;
      }
    }
    Note that this isn't the full code, I just included what's necessary to know (tell me if you need more)
    so the problem is that >> doesn't extract whitespace. As a result, lets say you have this in lol.txt:
    it would print this
    how do I fix this?
     
    Last edited by Nyap, Jul 20, 2016
  2. DaniloLemes

    DaniloLemes Newbie

    Newcomer
    9
    2
    Oct 4, 2012
    You want to just read a line and print it? 'Object oriented and logical' talking, you should just read the entire line and then store it somewhere and print.

    — Posts automatically merged - Please don't double post! —

    If I am right and you just want to read line by line, you can do this way:
    Code:
    int main () {
      string line;
      ifstream myfile ("example.txt");
      if (myfile.is_open())
      {
        while ( getline (myfile,line) )
        {
          cout << line << '\n';
        }
        myfile.close();
      }
    
      else cout << "Unable to open file";
    
      return 0;
    }