正在处理一个被给定的列表,例如用“,”分隔的程序,并将其内容放入向量中。
Test.txt包含:
“ 45001524”,“ MOCHI冰激凌弹”,“ LI”,“ 19022128593”,“ GT Japan,Inc。”,“ 2017-11-15 19:19:38”,“ 2017-11-15 19” :: 19:38“,”冰激凌成分:牛奶,奶油,糖,草莓(草莓,糖),玉米糖浆固体,SKIM牛奶,乳清,天然香料,瓜尔胶,单糖和甘油,甜菜汁和甜菜粉(FOR颜色),纤维素胶,豆荚胶,卡拉胶等。涂层成分:糖,水,米粉,海藻糖,鸡蛋白粉,甜菜汁和甜菜粉(用于颜色),玉米粉和马铃薯淀粉撒粉“
正在传递的readFile函数已经打开了test.txt,并试图将每个“,”分隔的字符串导入8种字符串类型的结构中。结构的名称是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)
我无法终生解决:\\我认为索引超出了文件的长度,但是我不确定如何补救。
答案 0 :(得分:1)
有些笨蛋没有增加他的itemNumber。将itemNumber ++添加到void readFile可解决此问题,并且现在可以正确读取。