简体   繁体   English

从文本文件中读取数据,并使用c ++语言将其存储在2D向量中

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

I am trying to read the data from the text file to the global 2D vector 'matrix The file content will be like : 我正在尝试将数据从文本文件读取到全局2D向量'矩阵。文件内容将如下所示:

8, 3 8、3

1, 6, 2 1 6 2

9, 2, 5 9 2 5

1, 5, 25 1 5 5

7, 4, 25 7、4、25

I could not figure out what is my mistake. 我不知道我的错误是什么。 my code store just the first row. 我的代码只存储第一行。

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

can some one tell me what is my mistake ? 有人可以告诉我我的错误是什么吗?

Change double while loop in your code with the following piece of code: 用下面的代码在代码中更改double 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);
    }

Reason of Failure: You are messing things up with the parsing of the ss stream, you need to introduce delimiters. 失败原因:您正在弄乱ss流的解析,需要引入定界符。

However, I wouldn't recommend such kind of parsing. 但是,我不建议这种解析。 C++11 supports regular expressions that make parsing smooth sailing. C ++ 11支持使解析顺利进行的正则表达式

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

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