【发布时间】:2015-04-07 03:09:18
【问题描述】:
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <cmath>
#include <cstdlib>
#include <sstream>
using namespace std;
int main(int argc, char* argv[])
{;
int arraylen = 7, arraylen_new = 0, i = 0, nextstep = 0;
string line, field, junkText;
string* randNum = new string[arraylen];
string* phrase = new string[arraylen];
ifstream randomTxt;
arraylen = 5;
randomTxt.open("random.txt");
while(!randomTxt.eof())
{
getline(randomTxt,line);
stringstream ss(line);
nextstep = 0;
while(getline(ss,field,','))
{
cout << i << endl;
/*if(nextstep == 0)
{
randNum[i] = field;
cout<< "number " << i << ": " << randNum[i] << endl;
nextstep = 1;
}
else if(nextstep == 1)
{
junkText = field;
cout<< "junk " << i << ": " << junkText << endl;
nextstep = 2;
}
else
{
items[i] = field;
cout<< "items " << i << ": " << items[i] << endl;
}*/
if(i == (arraylen-1))
{
arraylen_new = arraylen + 1;
string* temp1 = new string[arraylen_new];
string* temp2 = new string[arraylen_new];
copy(randNum, (randNum+arraylen), temp1);
delete [] randNum;
randNum = temp1;
copy(phrase, (phrase + arraylen), temp2);
delete [] phrase;
phrase = temp2;
arraylen = arraylen_new;
}
}
cout<<"test"<<endl;
i++;
}
randomTxt.close();
/*for(int i = 0; i < arraylen;i++)
{
cout<< "UPC " << i << ": " << UPC[i] << "\t" << "Phrase " << i << ": " << phrase[i] << endl;
}*/
return 0;
}
检查i 的值时,打印输出如下:
0
0
0
test
test
2
2
2
test
test
4
4
4
依此类推,直到我的文件被完全读取。我的迭代需要正确匹配,因为我使用它将每一行保存到单独的数组中。任何想法为什么它似乎跳过了内部 while 循环?
这是文本文件的sn-p:
333331234567,blah,"this is nonsense"
222221234567,word,"yadda yadda words"
111111234567,thing,"total gibberish stuff"
【问题讨论】:
-
@NathanOliver 好的,我的帖子已被编辑以包含链接中的代码。很抱歉造成混乱。
-
在修复了很多错误的语句(但没有逻辑)之后,你的代码对我来说是正确的。你确定这是正确的代码和文本文件吗?
-
免费建议:获取有关 RAII 的现代 C++ 书籍,忘记
string* randNum = new string[arraylen]。替换为std::vector<std::string> randNum(arraylen),您将节省大量时间。 -
我仅限于数组,所以没有向量。
-
This doesn't come close to compiling。还请删除任何不添加信息的 cmets,以便我们留下 minimal complete verifiable example。
标签: c++ file-io while-loop