Dylan Chensky Dylan Chensky - 2 months ago 19
C++ Question

Cannot convert from string to int using stoi

In my program first I read a file into a vector of strings called

rosterList
:


100

95

0

-1

110

80

90

-1

120

80

75

-1

130

60

55

-1


This step is successful. My goal is to create a vector of
Student
objects using the data above. Constructor accepts 3 strings as parameters:

Student::Student(string id,string g1,string g2)


To do that, the program loops through this vector of strings line by line, if the line converted to integer is greater or equal to 100, it is an id, then dynamically create a new
Student
object by passing the id (current line) and the next 2 lines as parameters, and add the object to the vector
studentRecords


for (vector<string>::iterator it = rosterList.begin(); it<rosterList.end();it++){
if(stoi(*it)>=100 || it == rosterList.begin()){ // error
studentRecords.push_back(
Student(*it,*(it+1),*(it+2)) // dynamically push
);
}
}


And there is a dynamic error:


libc++abi.dylib: terminating with uncaught exception of type
std::invalid_argument: stoi: no conversion


I looked it up online, the error comes from
stoi
not be able to convert. Where in the program goes wrong?

Answer

Either you have to read your file correctly....or If you are not confident on file data, do a validation for numeric content. Below is code sample. Any junk that you read other than numeric content in your file will cause failure. Below code compiles and for your idea. You can optimize it.

 #include <iostream>
    #include <cstring>
    #include <vector>
    #include <string>
    #include <algorithm>

    using namespace std;

std::vector<string> rosterList;
bool is_numeric(string strin)
{
    char const *str = strin.c_str();
    return all_of(str, str+strlen(str), 
                       [](unsigned char c) { return ::isdigit(c); });
}

int main(int argc, char *argv[])
{
    rosterList.push_back("100");
    rosterList.push_back(" ");
    rosterList.push_back("140");
    rosterList.push_back("180");


for (vector<string>::iterator it = rosterList.begin(); it<rosterList.end();it++){
        if(is_numeric(*it) && (stoi(*it)>=100 || it == rosterList.begin())){ // error

         std::cout<<stoi(*it)<<std::endl;
        }
    }
}
Comments