2011-11-24 35 views
4

我的教授非常聰明,但期望像我這樣的完全noobs知道如何編程。我不明白fstream函數如何工作。fstream ifstream我不明白如何將數據文件加載到我的程序

我將有一個包含三列數據的數據文件。我將不得不以對數來確定每行數據是否代表圓形,矩形或三角形 - 該部分很容易。我不明白的部分是fstream函數的工作原理。

我想我:

#include <fstream> 

那麼我應該聲明我的文件對象嗎?

ifstream Holes; 

然後我打開它:

ifstream.open Holes; // ? 

我不知道正確的語法是什麼,我無法找到簡單的教程。一切似乎比我的技能可以處理更先進。

此外,一旦我已經讀入數據文件什麼是正確的語法將數據放入數組?

我只是聲明一個數組,例如T[N]cinfstream對象Holes進去了嗎?

+2

也許可以查看這樣的教程:http://www.cplusplus.com/doc/tutorial/files/並向我們提出您可能遇到的任何具體問題。 – JoeFish

+2

請一次提出一個問題! –

+1

@JoeFish:那個教程是BS。不要使用它。 [謹防cplusplus.com](http://programmers.stackexchange.com/questions/88241/whats-wrong-with-cplusplus-com)。 –

回答

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"; 
    } 
} 

讓我們更進一步,假設我們要按照某種模式來處理每一行。我們使用以下字符串流:

#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"; 
    } 
1

讓我逐步瀏覽讀取文件的每個部分。

#include <fstream> // this imports the library that includes both ifstream (input file stream), and ofstream (output file stream 

ifstream Holes; // this sets up a variable named Holes of type ifstream (input file stream) 

Holes.open("myFile.txt"); // this opens the file myFile.txt and you can now access the data with the variable Holes 

string input;// variable to hold input data 

Holes>>input; //You can now use the variable Holes much like you use the variable cin. 

Holes.close();// close the file when you are done 

請注意,此示例不處理錯誤檢測。

相關問題