Reputation: 105
I have a .csv file that has around 5 rows and it looks something like this:
"University of Illinois, Chicago","1200, West Harrison","41.3233313","88.221376"
The first column is the name of the building, the second is the address and the third and fourth column represent the latitude and longitude. I want to take only the values in the 3rd and 4th column for every row.
If I use the getline method and separate every entry with ,
I do not get the desired result. Here is a sample of what I am doing:
ifstream file("Kiosk Coords.csv");
double latt[num_of_lines];
double longg[num_of_lines];
string name;
string address;
string latitude;
string longitude;
flag = 0;
while(file.good()){
getline(file,name,',');
getline(file,address,',');
getline(file,latitude,',');
getline(file,longitude,'\n');
//cout<<name<<" "<<address<<" "<<latitude<<" "<<longitude<<endl;
cout<<longitude<<endl;
}
For the above given input, I get the following values in the variable if I use my method:
name = "University of Illinois"
address = "Chicago
latitude = "1200"
longitude = "West Harrison,41.3233313,88.221376"
What I specifically want is this:
latitude = "41.3233313"
longitude = "88.221376"
Please help
Upvotes: 2
Views: 13478
Reputation: 3849
C++14's std::quoted to the rescue:
char comma;
file >> std::quoted(name) >> comma // name: University of Illinois, Chicago
>> std::quoted(address) >> comma // address: 1200, West Harrison
>> std::quoted(latitude) >> comma // latitude: 41.3233313
>> std::quoted(longitude) >> std::ws; // longitude: 88.221376
Upvotes: 8
Reputation: 37227
I think you have to manually parse it. Given that all elements are wrapped in quotes, you can easily extract them by just looking for the quotes.
Read a whole line then look for a pair quotes, and take the content between them.
std::string str;
std::getline(file, str);
std::vector<std::string> cols;
std::size_t a, b;
a = str.find('\"', 0);
while (true) {
b = str.find('\"', a + 1);
if (b != std::string::npos){
cols.push_back(str.substr(a, b-a));
}
a = str.find('\"', b + 1);
}
Results (double quote included):
cols[0]: "University of Illinois, Chicago"
cols[1]: "1200, West Harrison"
cols[2]: "41.3233313"
cols[3]: "88.221376"
Upvotes: 2