【发布时间】:2019-01-30 09:13:18
【问题描述】:
处理给定列表的程序,例如用“,”分隔,并将内容放入向量中。
Test.txt 包含:
"45001524","MOCHI ICE CREAM BONBONS","LI","19022128593","GT Japan, Inc.","2017-11-15 19:19:38","2017-11-15 19 :19:38","冰淇淋成分:牛奶、奶油、糖、草莓(草莓、糖)、玉米糖浆固体、脱脂牛奶、乳清、天然香料、瓜尔豆胶、单甘醇和甘油二酯、甜菜汁和甜菜粉(用于颜色)、纤维素胶、刺槐豆胶、角叉菜胶。包衣成分:糖、水、米粉、海藻糖、蛋清、甜菜汁和甜菜粉(上色),撒上玉米和马铃薯淀粉”
函数 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)
我这辈子都想不通:\我认为我的索引超出了文件的长度,但我不确定如何解决它。
【问题讨论】:
-
在调试器中运行时捕获异常,以定位它在代码中发生的位置。检查使用的索引,并与使用它们的字符串进行比较。
-
@Someprogrammerdude 我的最大 DB 大小为 30000,读取文件终止是 30000 的文件结尾,并且 vector
item(MAX_DB_SIZE);是启动,所以我认为这不是问题? -
你永远不会增加
itemNumber。如果你使用std::vector作为它的动态容器,你不需要手动跟踪元素的数量。 -
@molbdnilo 在这种情况下 test.txt 只有 1 个 itemNumber,在实际输入中,有几千行看起来都像 test.txt,并且对于每一个新行它都会增加。这在这里是否重要,因为这一切都应该在每行的基础上工作,并且它失败的 1 行尝试我相信它是别的什么?
-
我在子字符串周围添加了一个 if(index >= line.length()) else{ = line.substr(endIndex+1, index-endIndex-1);现在我得到一个 std::bad_alloc @Someprogrammerdude 的终止实例有什么想法吗?谢谢大家
标签: c++ string vector find fstream