Home > Net >  Ifstream to read "Name" column with multiple spaces in name c
Ifstream to read "Name" column with multiple spaces in name c

Time:08-01

I am trying to read a file using ifstream in c . The file has 5 columns and last column is the name column which contains the name with multiple spaces in the name. Some names have 1 and some have 2 spaces.

I want to read the name in a single variable instead of multiple ones. I have used :

while (infile >> recordDate >> relativeHumidity >> airTemp >> tempUnit >> name1 >> name2 >>> name3){}

Above code works fine for the names having 2 spaces but when it reads the line which has a name with one space the name3 varialble stores the first value of next line.

Date        RelativeHumidity        Air Temp     Units      Meteorologist Name
5/13/2009        1.096000          34.630000        C        D. Bernoulli
7/1/1903        0.313000           77.470000        f        Sir C. Wren

CodePudding user response:

Use getline to read to the end of line, that way you only need one variable.

while ((inFile >> recordDate >> relativeHumidity >> airTemp >> tempUnit) && std::getline(inFile, name))
{
}

CodePudding user response:

You could try something like the following:

while (infile)
{
        infile >> recordDate >> relativeHumidity >> airTemp >> tempUnit;
        getline(infile, name);
        const auto trim = [](const auto& s) {
            return s.substr(
                s.find_first_not_of(' ', 0),
                s.find_last_not_of(' ', 0)
            );
        };
        name = trim(name);
}
  • Related