Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to stop strange symbols from being read in the beginning of a getline string C++?

I have this function that imports strings from a .txt file, but when I import using getline the very first string shows up with 3 strange symbols attached to the front. Every other string comes out fine.

I don’t know if it’s the file itself, but I tried making a new file and it still reads in the strange symbols.

I tried a similar function with different data from a different .txt file (still strings) and I had no strange symbols at all.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

void SavagePlants::importInfo(std::fstream& importFile)
{
    plants = new PlantCare[numPlants];
    int i = 0;

    while (getline(importFile >> std::ws, plants[i].species, '#')) {

        getline(importFile, plants[i].sunlight, '#');
        wrapText(plants[i].sunlight);

        getline(importFile, plants[i].water, '#');
        wrapText(plants[i].water);

        getline(importFile, plants[i].temperature, '#');
        wrapText(plants[i].temperature);

        getline(importFile, plants[i].soil, '#');
        wrapText(plants[i].soil);

        getline(importFile, plants[i].fertilizer, '#');
        wrapText(plants[i].fertilizer);

        getline(importFile, plants[i].dormancy, '#');
        wrapText(plants[i].dormancy);
        ++i;
    }
}

This is what the output looks like for the first string:

Temperate Sundew

>Solution :

Your text file begins with a UTF-8 BOM (0xEF 0xBB 0xBF). You need to either:

  • create your UTF-8 text files without a BOM present.

  • just skip past those bytes before reading the rest of the file.

  • imbue() a UTF-8 locale into your fstream that knows how to recognize and ignore those bytes for you.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading