c++ - 不确定如何解决 'std::out_of_range' 错误

标签 c++ string vector find fstream

处理一个给定列表的程序,例如用“,”分隔并将内容放入 vector 中。

Test.txt 包含:

"45001524","MOCHI ICE CREAM BONBONS","LI","19022128593","G. T. Japan, Inc.","2017-11-15 19:19:38","2017-11-15 19:19:38","ICE CREAM INGREDIENTS: MILK, CREAM, SUGAR, STRAWBERRIES (STRAWBERRIES, SUGAR), CORN SYRUP SOLIDS, SKIM MILK, WHEY, NATURAL FLAVOR, GUAR GUM, MONO & DIGLYCERIDES, BEET JUICE AND BEET POWDER (FOR COLOR), CELLULOSE GUM, LOCUST BEAN GUM, CARRAGEENAN. COATING INGREDIENTS: SUGAR, WATER, RICE FLOUR, TREHALOSE, EGG WHITES, BEET JUICE AND BEET POWDER (FOR COLOR), DUSTED WITH CORN & POTATO STARCH"

函数 readFile 被传递给已经打开的 test.txt,并试图将每个“,”分隔的字符串导入到 8 种字符串类型的结构中。 Struct 的名称是 itemType。

int itemNumber 是计数。

void readFile( ifstream& inFile, vector<itemType>& item, int& itemNumber)
{


string currentLine;
int indexDef = 0;

while(getline(inFile, currentLine) && itemNumber < MAX_DB_SIZE){

    indexDef = 0;
    getQuotedString(currentLine, indexDef, item[itemNumber].NDBNumber);
    getQuotedString(currentLine, indexDef, item[itemNumber].longName);
    getQuotedString(currentLine, indexDef, item[itemNumber].dataSource);
    getQuotedString(currentLine, indexDef, item[itemNumber].upc);
    getQuotedString(currentLine, indexDef, item[itemNumber].manufacturer);
    getQuotedString(currentLine, indexDef, item[itemNumber].dataModified);
    getQuotedString(currentLine, indexDef, item[itemNumber].dataAvailable);
    getQuotedString(currentLine, indexDef, item[itemNumber].ingredients);
}

}

bool  getQuotedString( string& line, int& index, string& subString)
{
    int endIndex;
    //Start at 1st ' " '
    endIndex = index;
    //Find the next ' " '
    index = line.find('"', index+1);
    //subString = the characters between the first ' " ' and the second ' " '
    subString = line.substr(endIndex+1, index-endIndex-1);

    cout << subString << endl;

    //Move the second ' " ' over 2, passing over the comma and setting it on the next "
    index = index+2;
}

我正在使用 cout << subString用于测试。

它完美地输出了我想要的一切,但是在最后一次输出之后它抛出了一个错误

terminate called after throwing an instance of 'std::out_of_range' what(): basic_string::substr: __pos (which is 1) > this->size() (which is 0)
Aborted (core dumped)

我这辈子都弄不明白:\我认为我的索引超出了文件的长度,但我不确定如何补救。

最佳答案

有些白痴没有增加他的 itemNumber。将 itemNumber++ 添加到 void readFile 解决了问题,现在可以正常读取了。

关于c++ - 不确定如何解决 'std::out_of_range' 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54436974/

相关文章:

c++ - Windows Embedded Compact 7上发生意外的IConnectionPointImpl::Unadvise调用

java - 如何使用字符串调用方法

javascript - 如何在字符串值之前包裹内容?

python mpl : how to plot a point on a graph of 3D vectors, 和箭头头

r - 将向量列表组合到 data.frame 中,并带有列表编号

c++ - 从 C++ 调用时,MSSQL 服务器存储过程不返回输出参数

c++ - 自动创建一个定义对象的 vector ?

c++ - 在函数参数中分配/初始化引用

c++ - 获取字符串文字的字符长度

matlab - 在 Matlab 中绘制 3D 向量