使用
vector
vectors
#include <fstream>
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <iterator>
int main()
{
std::ifstream theStream("data.txt");
if (!theStream)
std::cerr << "data.txt\n";
std::vector<std::vector<int>> data; // vector to hold the numbers of each line seperately
while (true)
{
std::string line;
std::getline(theStream, line);
if (line.empty())
break;
std::istringstream myStream(line);
std::istream_iterator<int> begin(myStream), eof;
std::vector<int> numbers(begin, eof);
// process line however you need
data.push_back(numbers); // add numbers of current line to data
}
std::cout << data[1][2] << '\n'; // 2nd row, 3rd number: 103
}
假设查询只进行一次,则可以通过计算提取时所使用的行和列(以及while循环的每次迭代)一次完成;那就从那里离开。这样您就不必读取整个文件。
#include <cstddef>
#include <fstream>
#include <iostream>
#include <string>
#include <sstream>
int main()
{
std::ifstream theStream("data.txt");
if (!theStream)
std::cerr << "data.txt\n";
std::size_t target_row = 2; // 1-based
std::size_t target_col = 3; // 1-based
int value = 0;
int valid = false;
for (std::size_t current_row = 1; true; ++current_row)
{
std::string line;
if (!std::getline(theStream, line) || line.empty())
break;
if (current_row != target_row)
continue;
std::istringstream myStream(line);
for (std::size_t current_col = 1; myStream >> value; ++current_col)
if (current_col == target_col) {
valid = true;
break;
}
break;
}
if (!valid)
std::cerr << "No such row and column!\n\n";
else
std::cout << value;
}