[英]Read arrays of different length from multiple line file in C++
我有一个文件,看起来像这样:
0 0 1 4 6 17 43 20 21 7 0 1 6
0 2 1 9 14 16 79 283 35
1 0 1 2 2 0 0 0 0 0 0 1 4 0 3 5 7 9 11 4 1 30
1 1 0 1 5
还有更多不同长度的线。 我想将第一行读入一个数组,对这个数组做一些事情,然后再次将下一行读入数组(所以是一个循环)并使用这个数组。 总之-有一次我想从一行中获取一组值。
可以用数组而不是向量来做吗?
像这样的代码对我有用,但我在此处添加阅读下一行时遇到问题
int size = 13;
int arr[SIZE];
string inFileName = "file.txt";
ifstream inFile;
inFile.open(inFileName.c_str());
if (inFile.is_open())
{
for (int i = 0; i < size; i++)
{
inFile>>arr[i];
cout<<arr[i] << " ";
}
inFile.close();
}
大小对我来说不是问题,我可以从另一个文件中读取每一行。
提前致谢!
可以用数组而不是向量来做吗?
是的,可以使用数组来做到这一点,但为此您必须知道每行中元素的确切数量以及文件中有多少行。 更好的选择是使用std::vector<>
。
根据您的描述,您似乎想在读取文件后处理数组/向量。 为此,您可以使用 2D std::vector
,如下所示。
你的程序也有错误。 在 C++ 中,任何数组的大小都必须是编译时间常数。 所以举个例子:
int SIZE = 13;
int arr[SIZE];//INCORRECT because variable SIZE is not a constant expression
写上面的正确方法是:
const int SIZE = 13;
int arr[SIZE];//CORRECT
但是如果要使用数组,您必须知道输入文件中有多少行(行)和列(元素),这是不合适的。
您可以使用std::vector
以 2D 方式存储信息(如本例中的整数值)。 从文件中读取所有值后,您可以根据需要处理向量。 使用std::vector
的优点是您不必事先知道输入文件中的行数和列数。 因此,您不必事先为行和列分配 memory。 您可以动态添加值。 下面的程序从input.txt读取数据( int
值)并将其存储在 2D vector
中。
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include<fstream>
int main() {
std::string line;
int word;
std::ifstream inFile("input.txt");
//create/use a std::vector instead of builit in array
std::vector<std::vector<int>> vec;
if(inFile)
{
while(getline(inFile, line, '\n'))
{
//create a temporary vector that will contain all the columns
std::vector<int> tempVec;
std::istringstream ss(line);
//read word by word(or int by int)
while(ss >> word)
{
//std::cout<<"word:"<<word<<std::endl;
//add the word to the temporary vector
tempVec.push_back(word);
}
//now all the words from the current line has been added to the temporary vector
vec.emplace_back(tempVec);
}
}
else
{
std::cout<<"file cannot be opened"<<std::endl;
}
inFile.close();
//now you can do the whatever processing you want on the vector
//lets check out the elements of the 2D vector so the we can confirm if it contains all the right elements(rows and columns)
for(std::vector<int> &newvec: vec)
{
for(const int &elem: newvec)
{
std::cout<<elem<<" ";
}
std::cout<<std::endl;
}
return 0;
}
以上程序的output可以看这里。 上面提到的链接也给出了读取 int 值的输入文件。
TLDR:
你可以,但你必须至少知道每行中元素的最大数量,然后你创建一个缓冲区,其中可能有未使用的空间。
PS:
如果您担心重复的emplace_back
function,您可以立即将其放入向量中。
但是你不应该害怕emplace_back
function ,因为std::vector
做了一件聪明的事:
它在某个时候决定,它将保留已使用的空间的两倍。 这种方法将最小化重新分配的数量,因此它花费在emplace_back
上的时间平均为 O(1)(恒定速度)
免责声明:
在某些情况下,您可以搞砸向量的效率(可能不是int
s tho),但在大多数情况下,它可以得到缓解。 许多 cpp 会议演讲和许多博客文章等都是关于该主题的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.