从文本文件中读取数据,并使用c++语言将其存储在二维矢量中

read data from text file and store it in 2D vector using c++ language

本文关键字:存储 二维 语言 数据 读取 文件 文本 c++      更新时间:2023-10-16

我正在尝试将数据从文本文件读取到全局2D矢量矩阵文件内容如下:

8,3

1、6、2

9、2、5

1、5、25

7、4、25

我搞不清楚我的错误是什么。我的代码存储在第一行。

#include <iostream>
#include<fstream>
#include<algorithm>
#include<vector>
#include <sstream>
#define EXIT_FILE_ERROR (1)
#define EXIT_UNEXPECTED_EOF (2)
#define EXIT_INVALID_FIRSTLINE (3)
#define MAXLINE (10000)
std::vector< std::vector<int> > matrix;
int main(int argc, const char * argv[])
{
    FILE *fp;
    std::string sFileName = "Matrix1.txt";
    std::ifstream fileStream(sFileName);
    if (!fileStream.is_open())
    {
        std::cout << "Exiting unable to open file" << std::endl;
        exit(EXIT_FILE_ERROR);
    }
    std::string line;
    while ( getline (fileStream,line) )
    {
        std::stringstream ss(line);
        std::vector<int> numbers;
        std::string v;
        int value;
        while(ss >> value)
        {
            numbers.push_back(value);
            std::cout << value << std::endl;
        }
        matrix.push_back(numbers);
    }
    fileStream.close();
    if ((fp = fopen(sFileName.c_str(), "r")) == NULL)
    {
        std::cout << "Exiting unable to open file" << std::endl;
        exit(EXIT_FILE_ERROR);
    }
    return 0;
}

有人能告诉我我犯了什么错吗?

使用以下代码更改代码中的双while循环:

    while(getline(fileStream, line, 'n')) {
        std::stringstream ss(line);
        std::vector<int> numbers;
        std::string in_line;
        while(getline (ss, in_line, ',')) {
          numbers.push_back(std::stoi(in_line, 0));
        }
        matrix.push_back(numbers);
    }

失败原因:您在解析ss流时搞砸了,需要引入分隔符。

但是,我不建议使用这种解析C++11支持正则表达式,使解析顺利进行。