我正在编写一个程序,它根据从我的简单文件加载的数字创建 vector [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);
}
}
}
如果有人能帮助我,我将不胜感激。
最佳答案
根据你的问题:
I'm writing a program which creates vectors [x,y,z] from numbers loaded from my simple file, the numbers are separated just by the space.
您正在使用 C++(不是 C,如标签所声称的那样)进行编程,所以我很抱歉,但我不明白为什么您不做这样的事情(根本避免 strtok):
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
struct Vector {
double x,y,z;
// ... vector operations stuff...
// input operator
friend std::istream &operator>>( std::istream &is, Vector &v ) {
return is >> v.x >> v.y >> v.z;
}
// output operator
friend std::ostream &operator<<( std::ostream &os, Vector &v ) {
return os << v.x << ' ' << v.y << ' ' << v.z;
}
};
std::vector<Vector> readFile( const std::string &fname)
{
std::vector<Vector> main;
std::string buf;
Vector vtemp;
std::ifstream infile{fname, std::ios::in};
if (!infile.good()) {
std::cout << "cannot open the file!";
return main;
}
while ( infile >> vtemp ) {
main.push_back(vtemp);
}
return main;
}
int main() {
std::vector<Vector> data = readFile("input.txt");
std::cout << "Vectors read: " << data.size() << '\n';
for ( Vector & i : data ) {
std::cout << i << '\n';
}
return 0;
}
关于c - 使用 strtok() 的正确方法;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36262666/