Why does the beginning of my line disappear?

In the following C ++ code, I realized that it gcount()returns a larger number than I wanted, because it getline()consumes the final newline character, but does not send it to the input stream.

However, I still do not understand, this is the exit from the program. To enter "Test \ n", why am I getting "est \ n"? Why does my mistake affect the first character of the string, and not the addition of unnecessary garbage to the end? And why is the result of the program inconsistent with how the line looks in the debugger ("Test \ n", as you would expect)?

#include <fstream>
#include <vector>
#include <string>
#include <iostream>

using namespace std;

int main()
{
    const int bufferSize = 1024;
    ifstream input( "test.txt", ios::in | ios::binary );

    vector<char> vecBuffer( bufferSize );
    input.getline( &vecBuffer[0], bufferSize );
    string strResult( vecBuffer.begin(), vecBuffer.begin() + input.gcount() );
    cout << strResult << "\n";

    return 0;
}
+5
source share
4 answers

: Windows Vista, Visual Studio 2005 SP2.

, , .

: , . ( , ) - \r. , input.getline vecBuffer. getline \n, \r .

vecBuffer , gcount , , char, \n, vecBuffer - .

strResult:

-       strResult   "Test"
        [0] 84 'T'  char
        [1] 101 'e' char
        [2] 115 's' char
        [3] 116 't' char
        [4] 13 '␍'  char
        [5] 0   char

, "", ( ), ( T) , , \n, .

, \r, , vecBuffer, .

+12

Tommy Windows XP Pro 2 (SP2) , Visual Studio 2005 2 ( , " 8.0.50727.879" ), .

test.txt "Test" CR, "est" ( ) .

, , , Windows, Unix ( " ), , - .


Update: , , , . strResult , , . CR, Windows-land "\n", - " ". , :

string strResult (vecBuffer.begin(), vecBuffer.begin() + input.gcount() - 1);

... ( CR ), "", .

+6

, T , . rxvt (cygwin) . . ios:: binary , \r\n \n, , .

, "" ...- > Binary Editor. , \r\n, \n.

Edit: :

Test\r\0\r\n

, \0, , gcount 6 (6 ), , '\ 0'. , , '\ 0'. std::string 0 . , -, T, , , -, , , "\ 0"

cout << strResult.c_str() << "\n";

\0, .

+2

I tested your code with Visual Studio 2005 SP2 on Windows XP Pro SP3 (32-bit) and everything works fine.

+1
source

All Articles