从文件读取困难

问题描述 投票:0回答:1

我有一个用逗号分隔的值的文件

M,21,Hazel
F,49,Stephen

我正在将ifstream发送到使用istream读取行的函数中。

ifstream file(fileName);
char gender;
file.get(gender);
file.ignore();  // ignore comma

if (gender == 'M') {
  Gender* tmp = new Male;
  file >> *tmp;
} else if (gender == 'F') {
  Gender* tmp = new Female;
  file >> *tmp;
}

逗号前的第一个字符已正确读取,但是当我发送它以读取时,它会在不需要时要求用户输入。它不会读取文件的其余部分,即“ 49,Stephen”

istream& operator>>(istream& istr, ReadW& ref) {
  return ref.read(istr);
}

istream& read(istream& is) {
  char tName[16];
  is >> age;
  is.ignore();  // ignore comma
  is.getline(tName, 16, ',');
}
c++ fstream ostream istream
1个回答
0
投票

基本上,您是在问有关读取csv文件并将其拆分为令牌的问题。如果在SO上搜索此内容,您会发现很多帖子,其中解释了如何操作。

但是您的情况可能更简单。如果保证源文件的格式完全正确,并且在逗号前后没有多余的空格,则可以对流使用标准的提取器机制。您只需将逗号读入虚拟变量即可。可能看起来像:

// What we want to read
char gender{};
unsigned int age{};
std::string name{};
// This is a dummy
char comma{};

while (testDataStream >> gender >> comma >> age >> comma >> name) {

这将读取变量gender中的第一个字符,然后读取逗号并将其放入comma变量中。我们根本不会使用。然后,我们将继续以相同的方式提取更多的值。

如果源文件的结构不同,它将无法正常工作。例如,如果第一个变量是std::string,则testDataStream >> someString将读取直到下一个空格的完整行。但是,使用现有结构,它会起作用。

无论如何,您也可以使用其他功能,以防输入线格式不正确。也就是说,首先读取完整的一行,然后将其放入std::istringstream并从中提取数据。

如果您具有完全不同的数据结构,则可能会将该方法与带分隔符的std::getlinestd::regex_token_iterator一起使用。但这在这里就足够了。

此外,您显然具有班级等级。然后根据运行时读取的值创建派生类。这通常可以通过Abstract Factory模式解决。

我创建了一个可行的示例,您可以在其中看到所有这些机制。请注意:我将not使用纯C样式char数组作为字符串。并且,我将从不将原始指针用于拥有的内存。为此,应使用智能指针。

#include <iostream>
#include <sstream>
#include <memory>
#include <map>
#include <functional>

std::istringstream testDataStream(R"(F,21,Hazel
M,49,Stephen)");

// Abstract base class "Person"
struct Person {

    // Constructor
    Person(const unsigned int a, const std::string& n) : age(a), name(n) {}

    // Do not forget the virtual destructor
    virtual ~Person() { std::cout << "Destructor Base\n\n\n"; }

    // The data: name and age
    unsigned int age{};
    std::string name{};

    // Since the inserter is not none member function, we will write
    // a separate virtual function to do the job polymorph
    virtual std::ostream& output(std::ostream& os) const = 0;

    // Inserter, will call our internal output function
    friend std::ostream& operator << (std::ostream& os, const Person& p) {
        return p.output(os);
    }
};

// Derived class for a male Person
struct Male : public Person {
    // Constructor
    Male(const unsigned int age, const std::string& name) : Person(age, name) {}
    virtual ~Male() { std::cout << "Destructor Male\n"; }

    // And output
    virtual std::ostream& output(std::ostream& os) const override {
        return os << "Male Person:\nAge:\t" << age << "\nName:\t" << name << '\n';
    }
};

// Derived class for a female Person
struct Female : public Person {

    // Constructor
    Female(const unsigned int age, const std::string& name) : Person(age, name) {}
    virtual ~Female() { std::cout << "Destructor Female\n"; }

    // And output
    virtual std::ostream& output(std::ostream& os) const override {
        return os << "Female Person:\nAge:\t" << age << "\nName:\t" << name << '\n';
    }
};

// "Creation" Functions for abstract factory
std::unique_ptr<Person> createMale(const unsigned int age, const std::string& name) { return std::make_unique<Male>(age, name); }
std::unique_ptr<Person> createFemale(const unsigned int age, const std::string& name) { return std::make_unique<Female>(age, name); }

// Abstract factory
struct AbstractFactory {
    // Abbreviation for finding
    using Map = std::map<char, std::function<std::unique_ptr<Person>(const unsigned int, const std::string&)>>;
    Map creationFunctions{
        {'F', createFemale },
        {'M', createMale }
    };
    std::unique_ptr<Person> create(const char selector, const unsigned int age, const std::string& name) {
        // If the selector is in the map
        if (Map::iterator searchResult{ creationFunctions.find(selector) }; searchResult != creationFunctions.end())
            // Then we call the corresponding creation function
            return creationFunctions[selector](age, name);
        else
            // No key found, the return nullptr (Empty Person());
            return std::unique_ptr<Person>();
    }
};
// Our abstract factor
AbstractFactory abstractFactory{};

// Driver code
int main() {

    // What we want to read
    char gender{};
    unsigned int age{};
    std::string name{};
    // This is a dummy
    char comma{};
    std::string line{};

//#define DIRECT_READ 
#ifdef DIRECT_READ

    // As long as there is data in the stream, read the gender and the comma
    while (testDataStream >> gender >> comma >> age >> comma >> name) {

#else

    while (std::getline(testDataStream, line)) {
        std::istringstream iss{ line };
        if (iss >> gender >> comma >> age >> comma >> name) {

#endif

            // Create a Person, either male or female
            std::unique_ptr<Person> person = abstractFactory.create(gender, age, name);

            // Polymorphism. Call the adequate member function
            std::cout << *person << '\n';

            // Do other stuff 
            // . . . 

        }
#ifndef DIRECT_READ
    }
#endif
    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.