Strange problems with string class

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • creativeinspiration
    New Member
    • Jun 2007
    • 25

    Strange problems with string class

    Hey Guys. This is a weird one. Basically what I am doing is reading a string from the file using getline(file, buffer) where buffer is a C++ string. For example: lets say the file contains the string "hello" without the quotes on one line. After I read the file and print out the buffer it says "hello" (cout << buffer) like it should..BUT when I do this:

    buffer == "hello" , the answer is false. Why? I can't seem to see why. Furthermore, when I do cout << buffer << "." << endl;

    I get this output:

    .ello

    Why is this happening? In case you are wondering the file does not contain any blank spaces or lines after the string "hello". Any ideas?
  • Benny the Guard
    New Member
    • Jun 2007
    • 92

    #2
    How did you declare your string. getline take sin a char* not a std::string.

    As for the cout thing it looks like the operator<< on your string class is not workign quite right. It looks like it pushing the "." onto the string but in the front. Then it gets pushed to cout. This all hingees on your variable declaration.

    Comment

    • creativeinspiration
      New Member
      • Jun 2007
      • 25

      #3
      string buffer is how i declared it.

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        This works fine:
        [code=cpp]
        string buffer;
        getline(cin, buffer);
        if (buffer == "hello")
        {
        cout << "Equal" << endl;
        }
        cout << buffer << "." << endl;
        [/code]

        When I enter hello I get Equal displayed and hello.

        How is this ocde different from yours??

        Comment

        • Benny the Guard
          New Member
          • Jun 2007
          • 92

          #5
          Silly me I assumed he was using ifstream::getli ne () which only takes in a char*. But your right the version you use is a string. But it sounds like this is a file read, the only think I could think of why the comparison doesn't work is if end line is being added to the string. Can you copy your code up here for review?

          Comment

          Working...