我正在尝试将文本文件中的数据读取到全局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;
}
有人可以告诉我我的错误是什么吗?
答案 0 :(得分: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支持regular expressions ,使解析顺利进行。