基本ifstream
用法:
#include <fstream> // for std::ifstream
#include <iostream> // for std::cout
#include <string> // for std::string and std::getline
int main()
{
std::ifstream infile("thefile.txt"); // construct object and open file
std::string line;
if (!infile) { std::cerr << "Error opening file!\n"; return 1; }
while (std::getline(infile, line))
{
std::cout << "The file said, '" << line << "'.\n";
}
}
让我们更进一步,假设我们想根据某种模式处理每一行。我们为此使用字符串流:
#include <sstream> // for std::istringstream
// ... as before
while (std::getline(infile, line))
{
std::istringstream iss(line);
double a, b, c;
if (!(iss >> a >> b >> c))
{
std::cerr << "Invalid line, skipping.\n";
continue;
}
std::cout << "We obtained three values [" << a << ", " << b << ", " << c << "].\n";
}