将字符串向量转换为int

问题描述 投票:3回答:2

我必须制作一个程序,从一个文件中读取学生的信息,我做了几个向量来保存所有这些信息。但后来我需要总结所有学生的缺席,所以我需要将它们转换为整数,但是当我尝试程序运行时,但是当它到达atoi部分时立即崩溃。

while(!read.eof()) {
    if(i==4){
        i=0;
    }

    read>>b;

    if(i==0){ names.push_back(b); }
    if(i==1){ last_name.push_back(b); }
    if(i==2){ absences.push_back(b); }
    if(i==3){ unatoned.push_back(b); }
    i++;
}

int a = atoi(absences[0].c_str());
c++ string vector atoi
2个回答
3
投票

如果absences仍然是空的那么absences[0]的行为是不确定的。

absences.at(0)为空时使用absences强制编译器抛出异常,因此更容易使用。

无论哪种方式,对于缺席次数,请简单使用

auto a = absences.size();

0
投票

您应该将缺席向量更改为int的向量:

std::vector<int> abscences;

// rest of the code...

read >> var指令将负责转换。

当然,如果>>运算符无效,它将不会写入整数。

© www.soinside.com 2019 - 2024. All rights reserved.