0

Below code is to get some data from csv file. But the result is showing as follow:

5,Jones,123-123-1234,BCBS,GP1234,39,Sarah,Broken Arm,3

6,Smith,123-231-1234,UHC,G1234,47,Francine,Physical Therapy,03/25/2015

9,Adams,123-123-4321,Cigna,U1234,28,Bob,Broken Arm,2

5,Van Gogh,123-321-1234,BCBS,GP1235,37,Andrea,Tummy Ache,3

10,Pewterschmidt,123-312-1234,UHC,G1112,42,Peter,Supervision normal first pregnancy,03/26/2015

But I want to get the data except first column(such as 5,6,9,5,10) How can I do that? Could you give me an idea? Thanks.

void Hospital::readRecordsFile()
{
    fileName = "Waterbury Hospital patients records.csv";
    ifstream file(fileName);
    string value;
    vector <string> getInform;
    while(file.good())
    {
        getline(file, value);
        getInform.push_back(value);
        //getInform.erase(getInform.begin()+1);
    }

    for(int i=0;i<getInform.size();i++)
    {
        cout << getInform[i] << endl;
    }

}
Fred Larson
  • 60,987
  • 18
  • 112
  • 174
  • Check out this question, which even addresses why `while(file.good())` is wrong: https://stackoverflow.com/q/16446665/10077 – Fred Larson Mar 20 '18 at 19:55

3 Answers3

1

You can find first separator (,) in each line and then delete all charaters before it:

getline(file, value);
const auto pos = value.find(',');
if(pos != string::npos)
    value.erase(0, pos + 1);

If you are not sure about used separator character (,) in CSV file. You would probably do ignore all digits from the beginning of each line:

getline(file, value);
const auto pos = value.find_first_not_of("0123456789");
if(pos != string::npos)
    value.erase(0, pos + 1);
Anton Todua
  • 667
  • 4
  • 15
  • What if I changed getline(file, value) to getline(file, value, ',') ? Thank you sir! – GideokSeong Mar 20 '18 at 20:04
  • @GideokSeong You may write: getline(file, value, ','); getline(file, value); But I think that code above is more reliable, especially if comma (,) is not used as separator in CSV file. – Anton Todua Mar 20 '18 at 20:10
  • In csv file, each item in each row is seperated as a comma, so I neet to put comma, – GideokSeong Mar 20 '18 at 20:12
  • The first comma isn't necessarily the first separator in CSV. This code will fail if the first value is quoted and includes a comma. – Drew Dormann Mar 20 '18 at 20:41
1

std::istream::ignore can be used to ignore some of the text from an input stream.

Extracts and discards characters from the input stream until and including delim.

file.ignore(std::numeric_limits<std::streamsize>::max(), ',');

and follow it up with getline to read the rest of the line.

getline(file, value);
R Sahu
  • 204,454
  • 14
  • 159
  • 270
0

You should split each line by ',' and then ignore the first part.

Simply parse string to rich the first ',' character, then use substring from that index to end.

Arian B
  • 79
  • 1
  • 9