简体   繁体   中英

Reading from an Excel file

I am trying to read from an Excel file that has four columns and 121 rows. I tried the .csv idea, but I guess I understood it wrong because when I compile this, it gets all messed up.

How can I make sure city gets the first cell, country gets second, lon gets third, and lat gets fourth?

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
ifstream inFile;

string city;
string country;
string lat;
string lon; 
inFile.open("worldcities.csv");
if (inFile.is_open()) {
    cout << "File has been opened" << endl;
}
else {
    cout << "NO FILE HAS BEEN OPENED" << endl;
}


while (!inFile.eof()) {
    inFile >> city;
    inFile >> country;
    inFile >> lon;
    inFile >> lat;
    cout << "City: " << city << endl;
    cout << "Country: " << country << endl;
    cout << "Lat: " << lat << endl;
    cout << "Lon: " << lon << endl;
}
inFile.close();
system("pause");
return 0;
} 

Try this

while (!inFile.eof()) {
    getline ( inFile, city, ',' );
    getline ( inFile, country, ',' );
    getline ( inFile, lat, ',' );
    inFile >> lon;
    cout << "City: " << city << endl;
    cout << "Country: " << country << endl;
    cout << "Lat: " << lat << endl;
    cout << "Lon: " << lon << endl;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM