fstream ifstream我不明白如何加载数据文件到我的程序 [英] fstream ifstream I don't understand how to load a data file into my program
问题描述
我的教授很聪明,但希望像我这样的完整的noob只是知道如何编程 c ++ 。我不明白 fstream
函数是如何工作的。
我将有一个包含三列数据的数据文件。我将不得不用对数确定每一行数据是否代表一个圆,矩形或三角形 - 这部分很容易。我不明白的部分是如何 fstream
函数工作。
我认为我:
#include< fstream>
那么我应该声明我的文件对象吗?
ifstream Holes;
然后我打开它:
ifstream.open孔; //?
我不知道什么是正确的语法,我找不到简单的教程。一切似乎比我的技能可以处理更先进。
此外,一旦我读入数据文件,什么是正确的语法将数据放入数组?
我只是声明一个数组例如 T [N]
和 cin
fstream
object <$ c>基本 ifstream
#include< fstream& // for std :: ifstream
#include< iostream> // for std :: cout
#include< string> // for std :: string和std :: getline
int main()
{
std :: ifstream infile(thefile.txt); //构造对象并打开文件
std :: string line;
if(!infile){std :: cerr<< 打开文件时出错!\\\
; return 1; }
while(std :: getline(infile,line))
{
std :: cout< 文件说,<线<< '.\\\
;
}
}
让我们进一步假设我们要处理每行根据一些模式。我们使用字符串流:
#include< sstream> // for std :: istringstream
// ...如前面的
while(std :: getline(infile,line))
{
std :: istringstream iss(line);
double a,b,c;
if(!(iss>> a>> b> c))
{
std :: cerr< 无效的行,skipping.\\\
;
continue;
}
std :: cout<< 我们获得三个值[< a<< ,< b<< ,< c<< ] .\\\
;
}
My professor is very smart but expects complete noobs like me to just know how to program c++. I don't understand how the fstream
function works.
I will have a data file with three columns of data. I will have to determine with a logarithm whether each line of data represents a circle, rectangle or triangle - that part is easy. The part I don't understand is how the fstream
function works.
I think I:
#include < fstream >
then I should declare my file object?
ifstream Holes;
then I open it:
ifstream.open Holes; // ?
I don't know what the proper syntax is and I can't find straightforward tutorial. Everything seems way more advanced than my skills can handle.
Also, once I've read-in the data file what is the proper syntax to put the data into arrays?
Would I just declare an array e.g. T[N]
and cin
the fstream
object Holes
into it?
Basic ifstream
usage:
#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";
}
}
Let's go further and assume we want to process each line according to some pattern. We use string streams for that:
#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";
}
这篇关于fstream ifstream我不明白如何加载数据文件到我的程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!