从文本文件中读取数据,并使用c++语言将其存储在二维矢量中
read data from text file and store it in 2D vector using c++ language
我正在尝试将数据从文本文件读取到全局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支持正则表达式,使解析顺利进行。
相关文章:
- 带结构的二维矢量:如何存储元素
- 在二维向量或数组中可以存储的最大元素数是多少?
- 如何在二维数组中存储值?
- 如何将 numpy 二维数组作为一种可以用C++读取的二进制格式存储在磁盘上
- 如何在C++中将.csv文件的元素存储到二维向量中?
- 我无法将 Excel 中的输入字符串存储为二维字符串
- C++ ->尝试逐字阅读一行文本。如何使指针等效于用于存储输入的当前二维数组
- 使用什么数据结构来存储基于游戏对象的二维单元地图?
- 如何使用二维数组来计算和存储来自其他数组的值的频率
- 我如何在二维向量中存储一些数组
- 存储二维数组指针的方法是什么
- visual 将文件中的数据存储到C++中的二维数组中
- 从文件中读取整数并将其存储在二维矢量中
- 如何在二维数组中存储数据并使用2个循环显示二维
- 什么是快速矩阵或二维数组,用于在C++中存储邻接矩阵
- 如何在大型二维数组中存储数据
- 如何从文本文件中读取矩阵并将其存储到二维数组中
- 如何将字符变量存储为二维字符变量
- 存储具有不同列大小的动态分配的二维数组
- 如何在c++中按列主顺序存储二维数组中的值