gpt4 book ai didi

c++ - 如何在 C++ 中将空格和换行符分隔的整数读入二维数组?

转载 作者:可可西里 更新时间:2023-11-01 18:09:24 25 4
gpt4 key购买 nike

我有一个 .txt 文件,其中包含由空格分隔的数字(在本例中均小于 100),行中以换行符分隔。像这样:

 41 53 07 91 44
52 17 13 03 21

我想将这些数字读入一个二维数组,就像它们出现的那样,这样数组的列就用空格分隔,行就换行。

我可以让它以字符串的形式读取行,但是我在分离出单个数字并将它们视为整数时遇到了麻烦。

最佳答案

试试这个:

#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++ - 如何在 C++ 中将空格和换行符分隔的整数读入二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9570991/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com