使用strtok();

时间:2016-03-28 12:48:19

标签: c string object vector strtok

我正在编写一个程序,它从我的简单文件中加载的数字创建向量[x,y,z],这些数字仅由空格分隔。我使用Strtok()方法创建新的objets时遇到问题。这是代码。

#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;
}

创建wektors并将其推入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);
        }
    }
}

如果有人能帮助我,我会很高兴。

2 个答案:

答案 0 :(得分:0)

这是你正在寻找的吗?

#ifndef _STRING_H
#include <string>
#endif
#ifndef _FSTREAM_H
#include <fstream>
#endif
#ifndef _STREAMBUF_H
#include <streambuf>
#endif
#ifndef _VECTOR_H
#include <vector>
#endif

using namespace std;

void writeToFile(string path, string data) {
    ofstream ofs(path,ios::app);
    ofs << data;
    ofs.close();
}
string readFromFile(string path) {
    ifstream ifs(path);
    std::string ret((std::istreambuf_iterator<char>(ifs)),
        std::istreambuf_iterator<char>());
    return ret;
}

enum XYZ { X = 0, Y = 1, Z = 2 };

struct Vector {
    float x, y, z;
    Vector(float _x=0, float _y=0, float _z=0) {
        x = _x;
        y = _y;
        z = _z;
    }
    float& operator[](size_t index) {
        if (index == XYZ::X) return x;
        if (index == XYZ::Y) return y;
        if (index == XYZ::Z) return z;
        throw new exception;
    }
};



#define min(a, b) (((a) < (b)) ? (a) : (b))

bool isCharNumeric(char c) {
    const char* numbers = "0123456789";
    for (size_t index = 0; index < strlen(numbers); index++)
        if (c == numbers[index]) return true; return false;
}

vector<Vector> parseFloatVectors(string str_in) {
    str_in += "  "; //safe, no out of bounds
    vector<Vector> results = {};
    char currentChar;
    char skipChar = ' ';
    bool found_period = false;
    size_t count_len = 0;
    Vector vector_buffer(0,0,0);
    XYZ current_axis = (XYZ)0;
    for (size_t index = 0; index < str_in.length(); index++) {
        currentChar = str_in[index];
        if (currentChar == skipChar || currentChar == '\n' || currentChar == '\t')
            continue;

        else if (isCharNumeric(currentChar)) {
            string word = ""; //word buffer
            size_t word_len = min(min(str_in.find_first_of(' ', index + 1) - (index), str_in.find_first_of('\n', index + 1) - (index)), str_in.find_first_of('\t', index + 1) - (index)); //whatever char comes first; newline, tab or space
                                                                                                                                                              //append chars of following word checking if it is still valid number char
            if (word_len > 0) {
                size_t count_word_len = 0;
                for (count_word_len = 0; count_word_len < word_len; count_word_len++)
                    if (isCharNumeric(str_in[index + count_word_len])) {
                        word += str_in[index + count_word_len];
                    }
                    else if (str_in[index + count_word_len] == '.' && isCharNumeric(str_in[index + count_word_len + 1])) {
                        //Floating-point numbers
                        word += '.';
                        found_period = true;
                        continue;
                    }
                    else {
                        word = "";
                        continue;
                    }

                    vector_buffer[current_axis] = stof(word);


                    if (current_axis == XYZ::Z) {
                        current_axis = XYZ::X;
                        results.push_back(vector_buffer);
                    }
                    else {
                        current_axis = (XYZ)(current_axis + 1);
                    }


                    index += count_word_len;
                    word = "";
                    continue;
            }

        }
    }
    return results;
}

用法示例:     string input_floats = readFromFile(&#34; myVectors.txt&#34;);     vector vectors = parseNumbers(input_floats);

for each(Vector v in vectors) {
     printf("X = %f\n", v.x);
     printf("Y = %f\n", v.y);
     printf("Z = %f\n\n", v.z);
}

它只会解析完整的向量(一次3个浮点数)。换句话说,您最终只会得到一组完整的向量。

答案 1 :(得分:0)

从你的问题:

  

我正在编写一个程序,用数字创建矢量[x,y,z]   从我的简单文件加载,数字只是由   空间。

你是用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;
}
相关问题