stoi function gives error: std::invalid_argument at memory location 0x0035E8D8. c++

Publish date: 2024-05-05

The program runs fine until it gets to the stoi function, then the program breaks and gives me this error " Microsoft C++ exception: std::invalid_argument at memory location 0x0030EE7C." I've looked at tutorials on using stoi and I'm not sure what I'm doing wrong. The flat file reads like this:

Organic 7 description light 4 description menthol 5 description. 

with each word or number on a new line.

struct ProdDescriptor { string name; string price; string descript; }; void getProds() // reads products off of the flat file { int array = 3; ProdDescriptor x[3]; ifstream ItemRead(FlatFileName); // object of the flat file string temp; if (ItemRead.is_open()) // opens flat file and reads { for (int i = 0; i < array; i++) { ProdSpecPrice[i] = 0; // initialize getline(ItemRead, x[i].name); getline(ItemRead, x[i].price); getline(ItemRead, x[i].descript); temp = x[i].price; ProdSpecPrice[i] = stoi(temp); ProdSpecName[i] = x[i].name; ProdSpecDescription[i] = x[i].descript; } 
5

1 Answer

As from the reference documentation, std::stoi() must be expected to throw these exceptions:

Exceptions

std::invalid_argument if no conversion could be performed std::out_of_range if the converted value would fall out of the range of the result type or if the underlying function (std::strtol or std::strtoll) sets errno to ERANGE.

Thus this exception depends on your actual input, which you're currently not disclosing from your question (unfortunately).

11

ncG1vNJzZmirpJawrLvVnqmfpJ%2Bse6S7zGiorp2jqbawutJoampxYm2DeYKOrKuooV2bwq%2Bv06Kmp2WXnsOmv4yeqaunomLAtbDIp62apJmZeqK%2Bxq6knqakYq61ecyepKiqqWK5sK%2FAraCopl1lxXF8km6ccZxo