首页 > 解决方案 > 以 std::invalid_argument 类型的未捕获异常终止:stoi:无转换

问题描述

无法理解这个错误来自哪里。尝试按照示例教程进行操作,但我的版本不起作用。这是怎么回事?

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

https://www.geeksforgeeks.org/csv-file-management-using-c/

// C++ function
void read_record()
{

    // File pointer
    std::fstream fin;

    // Open an existing file
    fin.open("reportcard.csv", std::ios::in);

    // Get the roll number
    // of which the data is required
    int rollnum, roll2, count = 0;
    std::cout << "Enter the roll number "
        << "of the student to display details: ";
    std::cin >> rollnum;

    // Read the Data from the file
    // as String Vector
    std::vector<std::string> row;
    std::string line, word, temp;

    while (fin >> temp) {

        row.clear();

        // read an entire row and
        // store it in a string variable 'line'
        getline(fin, line);

        // used for breaking words
        std::stringstream s(line);

        // read every column data of a row and
        // store it in a string variable, 'word'
        while (std::getline(s, word, ',')) {

            // add all the column data
            // of a row to a vector
            row.push_back(word);
        }

        // convert string to integer for comparision
        roll2 = stoi(row[0]);

        // Compare the roll number
        if (roll2 == rollnum) {

            // Print the found data
            count = 1;
            std::cout << "Details of Roll " << row[0] << " : \n";
            std::cout << "Name: " << row[1] << "\n";
            std::cout << "Maths: " << row[2] << "\n";
            std::cout << "Physics: " << row[3] << "\n";
            std::cout << "Chemistry: " << row[4] << "\n";
            std::cout << "Biology: " << row[5] << "\n";
            break;
        }
    }
    if (count == 0)
        std::cout << "Record not found\n";
}
// terminal
max@Maxs-MacBook-Air csv % g++ -std=c++11 csv_practice.cpp -o csv_practice
max@Maxs-MacBook-Air csv % ./csv_practice
Enter the roll number of the student to display details: 1
libc++abi: terminating with uncaught exception of type std::invalid_argument: stoi: no conversion
// csv file
1,rahul,100,90,75,100
2,kaushik,90,80,50,90
3,nayonika,90,70,95,86
4,simran,55,85,70,70
5,sumana,65,90,95,100
max@Maxs-MacBook-Air csv % g++ -v
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/4.2.1
Apple clang version 12.0.5 (clang-1205.0.22.11)
Target: arm64-apple-darwin20.5.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin

标签: c++csvstoi

解决方案


推荐阅读