I have a problem with stoi where I'm using a getline from a csv file and getting the date,country,cases,death then using getline to get the date separated between month ,day, and year. However, I need to convert these dates to int, for some reason stoi breaks the code.
void fileOpener(){
ifstream file;
file.open("WHO-COVID-data.csv");
// stringstream ss;
string date1;
string country1;
string cases1;
string death1;
string month;
string day;
string year;
// string tempCountry;
string line;
// int num1 = 0;
// int num2 = 0;
vector<string> row;
vector<string> info;
while(!file.eof()){
getline(file,date1,',');
getline(file,country1,',');
getline(file,cases1,',');
getline(file,death1,'\n');
stringstream ss = stringstream(date1);
getline(ss,month,'/');
getline(ss,day,'/');
getline(ss,year,'/');
cout << month << "," << day << "," << year << endl;
examineString(month);
cout << ",";
examineString(day);
cout << ",";
examineString(year);
cout << endl;
int x = stoi(month);
cout << x << "," << stoi(day) << "," << stoi(year) << endl;
}
}
Inside CSV file
1/7/20,Afghanistan,23,4
1/8/20,Afghanistan,1534,345
1/9/20,Afghanistan,234,23
1/10/20,Afghanistan,563,63
1/12/20,Afghanistan,789,78
Expecting that it stoi the month, year, day
the code that you have there does not line up with the problem you have. I copied the code perfectly and was not able to reproduce your problem. The code i copied:
with the csv:
gave me the result:
So everything here, as i understand works fine. Now you can probably see i didn't use the 'examinestring()' function. I dont know what that is, and it's probably your own code that you didn't add here to your question, so i skipped it.
Now i understand that you do have a problem and here are a few things you should check/look out for:
make sure your file exists. If the code can't find the file, it wont be able to do stoi on the numbers which then will throw stoi exception.
make sure that the examinestring() function is not the thing thats throwing the stoi error
when opening files make sure to close them after
Also personally i'm not a big fan of that way of gathering data from files. I usually use this way:
Even though this above code looks a bit intimidating it's just a quick draft, it has a lot of potential for case improvement. Maybe it'll suit you better, maybe not, just throwing it out there.