【发布时间】:2016-03-28 12:48:18
【问题描述】:
我正在编写一个程序,它根据从我的简单文件中加载的数字创建向量 [x,y,z],这些数字仅由空格分隔。我在使用 Strtok() 方法创建新对象时遇到问题。这是代码。
#include "FileStaff.h"
vector<Vector>& FileStaff::readFile(string tekst)
{
vector<Vector> main;
string buffor;
char *text;
ifstream infile(tekst, ios::in);
//Checking if file exists
if (!infile.good()) {
cout << "cannot open the file!";
return main;
}
while (!infile.eof())
{
text = paraseStringToChar(tekst);
pushingToVector(main, text);
}
infile.close();
return main;
}
创建 wektor 并将它们推入 Vector 的方法。
void FileStaff::pushingToVector(vector<Vector>& main, char * tekst)
{
Vector *wektor = new Vector[1000000];
char korektor[] = " ";
float helpTab[3];
int wordCount=0;
char * container = strtok(tekst, korektor);
//counting numbers in our array
while (container != NULL)
{
container = strtok(NULL, " ");
wordCount++;
}
for (int i = 0; i <wordCount;i++ )
{
//Creating vectots [x,y,z]
container = strtok(tekst, korektor);
helpTab[i % 3] = atof(container);
container = strtok(NULL, korektor);
if (i % 3 == 0) {
Vector wektor(helpTab[0], helpTab[1], helpTab[2]);
main.push_back(wektor);
}
}
}
如果有人能帮助我,我会很感激的。
【问题讨论】:
-
既然有可以解析字符串的
std::string、std::stringstream和std::getline,为什么还要使用C 函数? -
最好的办法就是not to use
strtok()。 -
@πάνταῥεῖ 我已经使用
strtok()很多年了。排除使用string数据类型,为什么不使用strtok()?它似乎一直对我很有效。我很想知道您为什么建议避免使用它。 -
如果你使用的是 C 而不是 C++,你应该改变你的问题的标签:你会得到相关的答案。
-
@Logicrat 我的链接中提到的缺乏重新进入是这些原因之一。
标签: c string object vector strtok