[英]Parsing .txt file for double variable input in C++
Currently working on a snippet to input variables in which a user changes a text file to be used later.目前正在处理一个片段以输入变量,其中用户更改了稍后使用的文本文件。 Storing these in an array, and later referencing them for some openGL.
将这些存储在一个数组中,然后在某些 openGL 中引用它们。
The input text file looks something like this.输入文本文件看起来像这样。
something = 18.0;某事= 18.0;
something else = 23.4;别的东西= 23.4;
... 6 lines total ... 共 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();
Right now it is saving all the values in the array as initialized but not overwriting them later, as it should when I am breaking the lines into the tokens.现在它将数组中的所有值保存为已初始化但以后不会覆盖它们,就像我将行分成标记时那样。 Any help is appreciated.
任何帮助表示赞赏。
It looks to me like the bug is here:在我看来,这个错误就在这里:
n[i]=strtod(strtok(buf, ";"), NULL);
n[i]=strtod(strtok(buf, ";"), NULL);
On the first run through the while loop, strtok() will return a C string like "something = 18.0".在第一次运行 while 循环时,strtok() 将返回 C 字符串,例如“something = 18.0”。
And then strtod() will try to convert that to a double, but the string "something = 18.0" is not so easily converted to a double.然后 strtod() 将尝试将其转换为双精度,但字符串“something = 18.0”并不那么容易转换为双精度。 You'll want to tokenize the initial "something =" first, and throw that data out if necessary (or do something with it, if you want to).
您需要首先标记初始的“something =”,并在必要时丢弃该数据(或者如果您愿意,可以对其进行处理)。
You may want to refer to this thread to get ideas for some more C++-style ways to tokenize your string, instead of C-style like you're currently using:您可能需要参考此线程以获得更多 C++ 样式的字符串标记方法的想法,而不是您当前使用的 C 样式:
How do I tokenize a string in C++? 如何标记 C++ 中的字符串?
Good luck!祝你好运!
To apply what NattyBumppo had to say just change:要应用 NattyBumppo 所说的,只需更改:
n[i]=strtod(strtok(buf, ";"), NULL);
to:至:
strtok(buf," =");
n[i] = strtod(strtok(NULL, " ;"), NULL);
delete buf;
Of course, there are a lot of other ways to do it without strtok.当然,没有 strtok 的情况下还有很多其他方法可以做到这一点。
Here's one example:这是一个例子:
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() );
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.