【问题标题】:Parsing .txt file for double variable input in C++在 C++ 中为双变量输入解析 .txt 文件
【发布时间】:2011-08-15 16:54:03
【问题描述】:

目前正在使用 sn-p 来输入变量,用户可以在其中更改文本文件以供以后使用。将这些存储在一个数组中,然后在某些 OpenGL 中引用它们。

输入文本文件看起来像这样。

某事 = 18.0;

其他东西 = 23.4;

...共6行

//the variable of type ifstream:
ifstream patientInput(".../Patient1.txt");
double n[6]= {0.0,0.0,0.0,0.0,0.0,0.0};
register int i=0;
string line;
//check to see if the file is opened:
 if (patientInput) printf("Patient File Successfully Opened.\n");

else printf("Unable to open patient file\n");

 while(!patientInput.eof())
 {
    getline(patientInput,line);
    char *ptr, *buf;
    buf = new char[line.size() + 1];
    strcpy(buf, line.c_str());
    n[i]=strtod(strtok(buf, ";"), NULL);
    printf("%f\n",n[i]);
    i++;
 }
//close the stream:
patientInput.close();

现在它将数组中的所有值保存为已初始化但以后不会覆盖它们,就像我将行分成标记时那样。任何帮助表示赞赏。

【问题讨论】:

  • 为什么要随机混合 iostreams 和 C-style IO?
  • 这并不能解决您的问题,但您为什么要混合 C++ 和 C 风格的字符串?首先,您已经为自己设计了内存泄漏(指向buf 的内存到哪里去了?)。
  • 我看到,但是要使用 strtok,我必须创建 buf 才能从字符串转换为 char。不确定有什么其他方法可以解决这个问题。还有其他解决问题的方法吗?

标签: c++ text-parsing


【解决方案1】:

在我看来,错误就在这里:

n[i]=strtod(strtok(buf, ";"), NULL);

在第一次运行 while 循环时,strtok() 将返回一个 C 字符串,如“something = 18.0”。

然后 strtod() 将尝试将其转换为双精度,但字符串 "something = 18.0" 并不那么容易转换为双精度。您需要首先标记初始的“something =”,并在必要时丢弃该数据(或者根据需要对其进行处理)。

您可能希望参考此线程以获取更多 C++ 样式的字符串标记方法的想法,而不是您当前使用的 C 样式:

How do I tokenize a string in C++?

祝你好运!

【讨论】:

    【解决方案2】:

    要应用 NattyBumppo 所说的,只需更改:

    n[i]=strtod(strtok(buf, ";"), NULL);
    

    到:

    strtok(buf," =");
    n[i] = strtod(strtok(NULL, " ;"), NULL);
    delete buf;
    

    当然,没有 strtok 的情况下还有很多其他方法可以做到这一点。

    这是一个例子:

    ifstream input;
    input.open("temp.txt", ios::in);
    if( !input.good() )
        cout << "input not opened successfully";
    
    while( !input.eof() )
    {
        double n = -1;
        while( input.get() != '=' && !input.eof() );
    
        input >> n;
        if( input.good() )
            cout << n << endl;
        else
            input.clear();
    
        while( input.get() != '\n' && !input.eof() );
    }
    

    【讨论】:

      猜你喜欢
      • 2020-10-09
      • 1970-01-01
      • 2013-04-09
      • 1970-01-01
      • 1970-01-01
      • 2017-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多