如何使用C++获取所有STDIN
并解析它?
例如,我的输入是
2
1 4
3
5 6 7
我想使用 C++ 使用 cin 读取 STDIN
并将每一行存储在数组中。因此,它将是一个 vector/整数数组的数组。
谢谢!
最佳答案
由于这没有标记为作业,因此这里有一个使用 std::vector
和 std::stringstream 读取
s。我在最后添加了一个额外的部分,用于迭代 vector 并打印出值。给控制台一个 stdin
的小示例EOF
(ctrl + d for *nix, ctrl + z 对于 Windows)以阻止其读取输入。
#include <iostream>
#include <vector>
#include <sstream>
int main(void)
{
std::vector< std::vector<int> > vecLines;
// read in every line of stdin
std::string line;
while ( getline(std::cin, line) )
{
int num;
std::vector<int> ints;
std::istringstream ss(line); // create a stringstream from the string
// extract all the numbers from that line
while (ss >> num)
ints.push_back(num);
// add the vector of ints to the vector of vectors
vecLines.push_back(ints);
}
std::cout << "\nValues:" << std::endl;
// print the vectors - iterate through the vector of vectors
for ( std::vector< std::vector<int> >::iterator it_vecs = vecLines.begin();
it_vecs != vecLines.end(); ++it_vecs )
{
// iterate through the vector of ints and print the ints
for ( std::vector<int>::iterator it_ints = (*it_vecs).begin();
it_ints < (*it_vecs).end(); ++it_ints )
{
std::cout << *it_ints << " ";
}
std::cout << std::endl; // new line after each vector has been printed
}
return 0;
}
输入/输出:
2
1 4
3
5 6 7
Values:
2
1 4
3
5 6 7
编辑:向代码添加了更多注释。另请注意,可以将 int
的空 vector
添加到vecLines
(来自空输入行),这是故意的,以便输出与输入相同。
关于C++ cin 读取 STDIN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8627784/