Mohamed Elmalah Mohamed Elmalah - 11 days ago 6
C++ Question

Why is the first line shifted one space to the right?

Okay so me and a few colleagues were working on an assignment for class. I completed it to my fullest extent; however, there is one thing that neither I nor any of my colleagues could fix. I searched for hours online but couldn't fine the answer I needed.

The first line that is printed after the data is read from the file is always shifted 1 space to the right. That is my only problem. The string is not shifted, but everything is. We checked for spaces, tabs, and extra symbols, we tried switching up the file we were reading from all to achieve nothing. I would really appreciate it if someone could point out what is wrong with my program. Thanks in advance!

#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>

using namespace std;

int main() {

ifstream inputFile;

cout << "Please enter the file you would like to open: ";
string filename;
cin >> filename;

inputFile.open(filename);

if(inputFile.fail())
{
cout << "Error: File failed to open or was not found..." << endl;
}
else
{
cout << "File opened" << endl;

string land;
double price, min, max, total, average, count;

count = 0;
min = 0;
max = 0;
total = 0;

while(inputFile.good())
{
getline(inputFile, land, '\t');
inputFile >> price;

cout << fixed << setprecision(2) << setw(40) << left << land << right << "$ " << price;




if(count == 0)
{
max = price;
min = price;
}

if(price > max)
{
max = price;
}

if(price < min)
{
min = price;
}

total += price;


count++;
}

inputFile.close();

average = total / count;

cout << endl << endl;
cout << setw(43) << "Average Price = $ " << average << endl;
cout << setw(43) << "Highest Price = $ " << max << endl;
cout << setw(43) << " Lowest Price = $ " << min << endl;

}



return 0;
}


What doesn't make sense to me is that it is a loop, so why is only the first one being shifted?

This is what was on the file I was using

Landmark 1258
Creekside 1840
Parkside 1575
Gallatyn Walk 1710
Oak Mill 1185
Cutler's Ridge 1495
Prairie Creek Cottages 1987
Waterview Mills 1505
Canterbury Courts 1300
Breckinridge Point 1205
The Junction 1699


The words and numbers should all be separated with a tab.

The Image shows the output I was always given.
enter image description here

Answer

The difference is that from the first line, variable "land" is "Landmark" while all the others have the \n in front of the name, taken from the previous line, ie "\nCreekside", "\nParkside" etc. You could just delete the \n from the string name and then add it at the end of your std::cout:

while (inputFile.good())
    {
        getline(inputFile, land, '\t');

        if (land[0] == '\n')
        {
            land.erase(0, 1);
        }


        inputFile >> price;

        cout << fixed << setprecision(2) << setw(40) << left << land << right << "$   " << price << endl;

Now the outcome is formatted correctly!