读取文本文件并将数据存储到多个数组C 中

Reading a text file and storing data into multiple arrays C++

本文关键字:数组 存储 文件 取文本 数据 读取      更新时间:2023-10-16

我正在尝试读取一个数据库文件(作为txt),我想跳过空行并跳过文件中的列标头线,然后将每个记录存储为一个数组。我想乘stop_id并适当地找到stop_name。即。

如果我说给我停止17,该程序将获得"杰克逊& kolmar"。

文件格式如下:

17,17,"Jackson & Kolmar","Jackson & Kolmar, Eastbound, Southeast  Corner",41.87685748,-87.73934698,0,,1
18,18,"Jackson & Kilbourn","Jackson & Kilbourn, Eastbound, Southeast Corner",41.87688572,-87.73761421,0,,1
19,19,"Jackson & Kostner","Jackson & Kostner, Eastbound, Southeast Corner",41.87691497,-87.73515882,0,,1

到目前为止,我能够获得stop_id值,但是现在我想获得停止名称值,并且是C 字符串操作的新事物

mycode.cpp

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
    string filename;
    filename = "test.txt";
    string data;
    ifstream infile(filename.c_str());
    while(!infile.eof())
    {
        getline(infile,line);
        int comma = line.find(",");
        data = line.substr(0,comma);
        cout << "Line " << count << " "<< "is "<< data << endl;
        count++;
    }
    infile.close();
    string sent = "i,am,the,champion";
 return 0;
}

您可以使用string::find 3次搜索逗号的第三次出现,并且您必须存储line中发现的最后2个出现的位置,然后将其用作输入数据,然后使用string::substr并获取搜索文本:

std::string line ("17,17,"Jackson & Kolmar","Jackson & Kolmar, Eastbound, Southeast  Corner",41.87685748,-87.73934698,0,,1");
std::size_t found=0, foundBack; 
int i;
for(i=0;i<3 && found!=std::string::npos;i++){   
    foundBack = found;
    found=line.find(",",found+1);
}
std::cout << line.substr(foundBack+1,found-foundBack-1) << std::endl;

您可以读取文件的整个行ITO inA字符串,然后使用stringstream一次为您提供一次,直到直到逗号。然后,您可以填充阵列。我假设您想要自己的数组中的每一行,并且想要无限的数组。最好的方法是拥有一系列数组。

std::string Line;
std::array<std::array<string>> Data;
while (std::getline(infile, Line))
{
    std::stringstream ss;
    ss << Line;
    Data.push_back(std::vector<std::string>);
    std::string Temp;
    while (std::getline(ss, Temp, ','))
    {
        Data[Data.size() - 1].push_back(Temp);
    }
}

这样,您将拥有一个矢量,充满了向量,每个矢量都在该行中所有数据的字符串。要访问字符串作为数字,您可以使用将字符串转换为整数的std::stoi(std::string)