【发布时间】:2014-05-25 22:37:24
【问题描述】:
这里,抱歉,如果这个问题不适合这个论坛。我对编程很陌生,并认为通过创建这个小项目可以更好地掌握字符串和文件。我要做的是从 JSON 文档中提取数据。最终我会将数据存储在一个数组中,然后再使用它。
基本上,我想知道是否有更好的方法来解决这个问题。代码看起来有点罗嗦,绝对不优雅。再次抱歉,如果这个问题不是一个好问题,但我认为没有比通过这样的社区更好的学习方式了。
#include <iostream>
#include <fstream>
#include <cstring>
#include <string> //probably including more than necessary
using namespace std; //should be specifying items using scope resolution operator instead
int main(int argc, const char * argv[])
{
ifstream sfile("JSONdatatest.txt");
string line,temp;
while(!sfile.eof()){
getline(sfile, line);
temp.append(line); //creates string from file text, use of temp seems extraneous
}
sfile.close();
cout << "Reading from the file.\n";
size_t counter=0;
size_t found=0;
size_t datasize=0;
while(found!=string::npos && found<1000*70){ //problem here, program was creating infinite loop
//initial 'solution' was to constrain found var
//but fixed with if statement
found = temp.find("name: ",counter);
if(found!=string::npos){
found=found+7; //length of find variable "name: ", puts us to the point where data begins
size_t ended=temp.find_first_of( "\"", found);
size_t len=ended-found; //length of datum to extract
string temp2(temp, found, len); //odd use of a second temp function,
cout << temp2 << endl;
counter=ended+1;
datasize++; //also problem with data size and counter, so many counters, can they
//coordinate to have fewer?
}
}
cout << datasize;
return 0}
在我指出进行了无限循环的地方,我通过在 while 循环中添加 if 语句来修复。我的猜测是因为我将 7 添加到 'found' 中,它有可能跳过 npos 并且循环继续。添加 if 语句修复了它,但使代码看起来很笨重。必须有一个更优雅的解决方案。 提前致谢!
【问题讨论】:
-
您没有使用 JSON 解析器是否有原因?
-
可以使用第三方库的 JSON 解析器吗?例如,卡萨布兰卡项目中有一个。看看吧。
-
感谢 cmets。我环顾四周,并认为我最终会使用它增加的功能。 @WilliamAndrewMontgomery 我希望借此更好地理解字符串和文件,但可能不是最好的项目创意,哈哈。