繁体   English   中英

读取逗号分隔的txt文件为arrays C++ cpp

[英]reading a txt file separated by commas into arrays C++ cpp

C++ 问题。 我有一个包含此信息的:txt 文件:

james, watson
brittany,blake
roger,tra4@pos
jonathan, pote5
amber,Trisa123!

其中第一列是名称,第二列是网站用户的 Id。

我需要读取此文件,然后将信息存储到 2 arrays: name[] user_Id [] 你能帮帮我吗? 我找到了将其保存到二维向量中的解决方案,但我更愿意将其保存为 arrays,因为我需要将字符串值与另一个字符串进行比较(由用户接收以检查她的姓名/用户 ID 是否已在系统中)

我找到了将其保存到 2d 矢量但不是 arrays 的解决方案。

我将向您展示您所要求的解决方案,但很遗憾地通知您,该解决方案的方法是错误的。 由于各种原因。 首先,也是最重要的:在 C++ 中,C-Style arrays 通常应该被使用。

C 样式 arrays 具有固定大小并且不是动态的。 所以,你总是会想出一个估计最大大小的幻数。 正确的方法是使用动态容器。 对于您的解决方案, std::vector是最合适的。

然后,为了相关数据必须分离 arrays 是一个非常糟糕的主意。 正确的做法是将相关数据放在一个struct中,然后创建一个该结构体的std::vector 否则你将不得不一直维护和处理2 arrays,甚至可能失去相关数据之间的同步。

无论如何,我将首先向您展示一个按照您的想法的解决方案:

#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;

const unsigned int MagicNumberForMaxArraySize = 42;

int main() {

    // Define Arrays to hold the user and their IDs
    string user[MagicNumberForMaxArraySize]{};
    string user_ID[MagicNumberForMaxArraySize]{};

    // Open the file and check, if it could be opened
    ifstream ifs("test.txt");
    if (ifs.is_open()) {

        unsigned int index = 0;
        // Read all lines and put result into arrays
        while ((index < MagicNumberForMaxArraySize) and 
            (getline(getline(ifs, user[index], ',') >> ws, user_ID[index]))) {
            // Now we have read a comlete line. Goto next index
            ++index;
        }
        // Show debug output
        for (unsigned int i = 0; i < index; ++i)
            cout << "User: " << user[i] << "\tID: " << user_ID[i] << '\n';
    }
    else
        cout << "\n\n*** Error: Could not open source file\n\n";
}

但我不会推荐给 go。 下一个改进是使用struct ,然后使用结构数组。 另外,我将摆脱using namespace std; 永远不应该使用。 而且,我使用通用初始化器初始化变量。

#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>


const unsigned int MagicNumberForMaxArraySize = 42;

struct Data {
    std::string user{};
    std::string ID{};
};

int main() {

    // Define array for our needed data
    Data data[MagicNumberForMaxArraySize];

    // Open the file and check, if it could be opened
    std::ifstream ifs("test.txt");
    if (ifs.is_open()) {

        unsigned int index = 0;
        // Read all lines and put result into arrays
        while ((index < MagicNumberForMaxArraySize) and 
            (std::getline(std::getline(ifs, data[index].user, ',') >> std::ws, data[index].ID))) {
            // Now we have read a comlete line. Goto next index
            ++index;
        }
        // Show debug output
        for (unsigned int i = 0; i < index; ++i)
            std::cout << "User: " << data[i].user << "\tID: " << data[i].ID<< '\n';
    }
    else
        std::cout << "\n\n*** Error: Could not open source file\n\n";
}

进化:

下面介绍一个面向object的原理。 操作此数据的数据和方法应在一个classstruct中。 因此,我们将向struct添加 IO 方法,并添加一个附加struct来保存所有用户。 此外,可以使用带有初始值设定项的新if语句。 当然还有std::vector

请参阅:

#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
#include <vector>

// Struct to hold properties for one user
struct User {
    std::string name{};
    std::string ID{};

    // Simple extraction
    friend std::istream& operator >> (std::istream& is, User& user) {
        std::getline(std::getline(is, user.name, ',') >> std::ws, user.ID);
        return is;
    }
    // Simple inserter
    friend std::ostream& operator << (std::ostream& os, const User& user) {
        return os << "User: " << user.name << "\tID: " << user.ID;
    }
};
// This class will contain all users
struct Data {
    std::vector<User> users{};
    // Simple extraction
    friend std::istream& operator >> (std::istream& is, Data& d) {
        // Delete potential existing old data
        d.users.clear();
        // Now read all users
        for (User temp{}; is >> temp; d.users.push_back(std::move(temp)));
        return is;
    }
    // Simple inserter
    friend std::ostream& operator << (std::ostream& os, const Data& d) {
        for (const User& u : d.users) os << u << '\n';
        return os;
    }
};

int main() {
    // Open the file and check, if it could be opened
    if (std::ifstream ifs("test.txt");ifs) {

        // Read all data and show result
        if (Data data{}; not (ifs >> data).bad())
            std::cout << data;
    }
    else
        std::cout << "\n\n*** Error: Could not open source file\n\n";
}

您还可以使用cstring库中的strtok()将字符串拆分为标记: Split string in C/C++

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM