lpr*_*er1 4 c++ fstream ifstream ofstream
我的教授非常聪明,但我希望像我这样的完全新手只知道如何编写c ++.我不明白这个fstream功能是如何工作的.
我将有一个包含三列数据的数据文件.我将不得不用对数确定每行数据是否代表圆形,矩形或三角形 - 这部分很容易.我不明白的部分是该fstream功能的工作原理.
我想我:
#include < fstream >
Run Code Online (Sandbox Code Playgroud)
那我应该声明我的文件对象?
ifstream Holes;
Run Code Online (Sandbox Code Playgroud)
然后我打开它:
ifstream.open Holes; // ?
Run Code Online (Sandbox Code Playgroud)
我不知道正确的语法是什么,我找不到简单的教程.一切似乎都比我的技能处理得更先进.
此外,一旦我读入数据文件,将数据放入数组的正确语法是什么?
请问我只是声明数组如T[N]与cin该fstream物体Holes成吗?
Ker*_* SB 10
基本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";
}
}
Run Code Online (Sandbox Code Playgroud)
让我们进一步假设我们想要根据某种模式处理每一行.我们使用字符串流:
#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";
}
Run Code Online (Sandbox Code Playgroud)