[英]How to read text file lines into vectors?
我需要将输入文件中的一些行读入向量(整数)中,而 c++ 对我来说是新的,所以我无法理解具有很多功能的巨大代码。你能告诉我如何以最基本的方式做到这一点吗?
在我的文件中,我有这样的东西:
5 6 11 3 4
2 3 1
1
9
我用另一个程序编写了输入文件,因此如果我使阅读更容易,我可以在其中显示向量的数量(在这种情况下为 4)及其大小(5、3、1、1)。
我的意思是我可以以任何形式呈现信息......只需要知道哪个更好以及如何使用它..
这是一个简单的示例,其中std::istringstream
用于提取每行的值。
(请注意, 在阅读之前不必调用eof() 。)
std::ifstream file("file.txt");
std::vector<std::vector<int>> vectors;
std::string line;
while (std::getline(file, line))
{
std::istringstream ss(line);
std::vector<int> new_vec;
int v;
while (ss >> v) // populate the new vector
{
new_vec.push_back(v);
}
vectors.push_back(new_vec); // append it to the list of vectors
}
file.close();
这并不是真正的“基本方法”,但是它很简短,并且可以起作用:
#include <fstream>
#include <iterator>
#include <sstream>
#include <string>
#include <vector>
int main()
{
std::vector<std::vector<int>> vec;
std::ifstream file_in("my_file.txt");
if (!file_in) {/*error*/}
std::string line;
while (std::getline(file_in, line))
{
std::istringstream ss(line);
vec.emplace_back(std::istream_iterator<int>(ss), std::istream_iterator<int>());
}
}
略有简化的版本,具有相同的功能:
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
int main()
{
std::vector<std::vector<int>> vec;
std::ifstream file_in("my_file.txt");
if (!file_in) {/*error*/}
std::string line;
while (std::getline(file_in, line)) // Read next line to `line`, stop if no more lines.
{
// Construct so called 'string stream' from `line`, see while loop below for usage.
std::istringstream ss(line);
vec.push_back({}); // Add one more empty vector (of vectors) to `vec`.
int x;
while (ss >> x) // Read next int from `ss` to `x`, stop if no more ints.
vec.back().push_back(x); // Add it to the last sub-vector of `vec`.
}
}
我不会将stringstreams称为基本功能,但是如果没有它们,做您想做的事情会更加混乱。
这应该做的工作:
int n; char c;
vector<int> vectors[4];
//variable to record what vector we are currently looking
int vectorIndex = 0;
//reading an integer while it's possible
while(scanf("%d", &n)){
//reading char, if couldn't read, breaks out of the loop
if(!scanf("%c", &c)) break;
//adding the integer we've just read into the vectorIndex-th vector
vectors[vectorIndex].push_back(n);
if(c == '\n') vectorIndex++;
}
首先,我们声明一个带有一些向量的数组(如果您想要更动态的东西,则可以有一个整数向量的向量)。
然后我们简单地读取一个int(有一个int),然后读取一个char。 如果char是\\n
,我们知道我们的向量已经结束,然后我们转到下一个(使用vectorIndex
表示当前正在向哪个向量中添加元素)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.