【发布时间】: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