S.W
S.W

Reputation: 3

String not printing using std::cout

When trying the print the contents of the readdata string the result is not as expected, however if I individually print out the contents of 'line' the correct result is printed:

std::string line;
std::string readdata;
std::ifstream file(filename);
if (file.is_open()) 
{
    for (int i=0;std::getline(file,line) && i<10;i++)
    {
        std::cout<<line<<std::endl;    //Prints correct result for each instance.
        readdata.append(line); 
        if (i!=9)
        {
            readdata.append(" ");
        }

    }
    std::cout<<readdata<<std::endl;    //Prints garbled result.
    file.close();   
}

The text file being read contains this data:

#+/084&"
#3*#%#+
8%203:
,1$&
!-*%
.#7&33&
#*#71%
&-&641'2
#))85
9&330*

The printing of 'line' prints this, but when readdata is printed the result is:

9&330*'2

Upvotes: 0

Views: 221

Answers (2)

Vladimir Kunschikov
Vladimir Kunschikov

Reputation: 1763

    readdata.append(line.substr(0, line.find("\r")));

Upvotes: 1

Zaskar
Zaskar

Reputation: 599

I think you are getting a '\r' at the end of each line.

Upvotes: 8

Related Questions