本文介绍了如何在C ++中将空格和换行符分隔的整数读取为2D数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个由空格分隔的.txt文件(在这种情况下,所有小于100),用新行分隔的行。像这样:
I have a .txt file of numbers (in this case all less than 100) separated by spaces, in rows separated by new lines. Something like this:
41 53 07 91 44
52 17 13 03 21
我想读这些数字到一个2d数组,就像它们出现,使空格分隔数组的列,单独的行。
I would like to read these numbers into a 2d array, exactly as they appear, so that spaces separate columns of the array, and new lines separate rows.
我可以让它以字符串形式读取行,但是我无法分离出单个数字,并将其作为整数处理。 p>
I can get it to read the lines in as strings, but then I'm having trouble separating out individual numbers, and getting it to treat them as integers.
推荐答案
尝试:
#include <vector>
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
int main()
{
// The result of the read is placed in here
// In C++, we use a vector like an array but vectors can dynamically grow
// as required when we get more data.
std::vector<std::vector<int> > data;
// Replace 'Plop' with your file name.
std::ifstream file("Plop");
std::string line;
// Read one line at a time into the variable line:
while(std::getline(file, line))
{
std::vector<int> lineData;
std::stringstream lineStream(line);
int value;
// Read an integer at a time from the line
while(lineStream >> value)
{
// Add the integers from a line to a 1D array (vector)
lineData.push_back(value);
}
// When all the integers have been read, add the 1D array
// into a 2D array (as one line in the 2D array)
data.push_back(lineData);
}
}
这篇关于如何在C ++中将空格和换行符分隔的整数读取为2D数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!