Skip to main content
GameDev.net gamedev.net
🔒 Locked

fstream question

Started by Kris2456 Jan 9, 2005 at 12:27 PM 1 replies 650+ views
Original Post
Kris2456
Kris2456
Hi, ever since i moved on to using fstream rather than fopen, etc. I have gotten a bit confused with how to read files. Assuming i have a file like this, and i want to read the number after the 'T' every time, how would i do this. The file looks like this:

T 1
T 1
T 2
T 4
T 7
T 4
....

------------ "Here lies a toppled God,His fall was not a small one,We but built his pedastle,A narrow, and a tall one" Frank Herbert (Dune:Messiah)
jflanglois
jflanglois
You'd do something like this (assuming T means something):

#include <fstream>#include <iostream>using namespace std;int main() {  ifstream fin( "file.txt" );  if ( !fin ) {    cerr << " !! Invalid Filename" << endl;    cin.get();    return 1; // Filename is wrong, should try and recover instead of exitting  } // if  char command;  int param;  while ( fin >> command >> param ) { // while not EOF    // process values, for instance:    if ( command == 'T' ) {      if ( param == 1 )        cout << " :: Do T with a value of 1" << endl;      else if ( param == 2 )        cout << " :: Do T with a value of 2" << endl;      //else if ...      else cerr << " !: Invalid value for T" << endl;    } // if    else cerr << " !: Invalid command" << endl;  } // while  cin.get();  return 0;} // int main


'command' will hold 'T' and param will hold 1, 1, 2, 4, 7, 4 in your example

[edit] Note that I use ifstream instead of fstream to simplify things. fstream resembles fopen a little more because you have to pass in the "open mode" in the constructor or open method

'fin >> command >> param' is a sort of chain of method calls. you could write it
'fin >> command;
fin >> param;'
if you liked. The stream extraction operator (>>) will jump over whitespaces (newline, space, tab) to get to the next appropriate value. You could open the file in binary mode, in which it won't "jump" over whitespace.

[Edited by - jflanglois on January 9, 2005 1:43:35 PM]
snk_kid
snk_kid
alternative methods:

input file: test.txt

T 1T 1T 2T 4T 7T 4


code:
#include <algorithm>#include <iterator>#include <string>#include <vector>#include <fstream>#include <sstream>#include <iostream>int main() {   const char delim = 'T';   std::ifstream ifs("test.txt");   std::string buf;   std::remove_copy(std::istreambuf_iterator<char>(ifs),                    std::istreambuf_iterator<char>(),                    std::back_inserter(buf), delim);   ifs.close();   std::istringstream iss(buf);   std::vector<int> v((std::istream_iterator<int>(iss)),                       std::istream_iterator<int>());   std::copy(v.begin(), v.end(),             std::ostream_iterator<int>(std::cout, ", "));}


output:
1, 1, 2, 4, 7, 4,

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.