Another .dat question

Started by
8 comments, last by Crazyfool 17 years ago
Howdy, OK, I am doing this to write to a .dat file:


ofstream file;
int noob=50;

file.open("thingy.dat");

file << "NOOB: " << endl;
file << noob << endl;




Then I open the .dat file with NOTEPAD and edit the "noob" variable to 100. How do I then read/extract the "noob" variable? I tried this but it doesn't work:


ifstream file;
int noob;

file.open("thingy.dat");

file >> noob;



That code doesn't read the "noob" variable. Which brings me to my main question. How do I read the "noob" variable if it comes after a string "NOOB: "? [Edited by - Acid rain on April 7, 2007 6:50:55 PM]
------------------------------Trust me, I do this all the time.
Advertisement
You need to open the file first:

ifstream file;int noob;file.open("thingy.dat");file >> noob;
Whoops, that was just a typo. I am opening teh file first. But then what?
------------------------------Trust me, I do this all the time.
You write two things to the file (the string "NOOB: " and then an integer) but you only try to extract one thing, the integer. You have to read in the text first to reach the integer value.
#include <string>#include <fstream>void f(){    std::ifstream is("whatever.dat");    std::string s;    int noob;    is >> s >> noob;}
also, should close the file when your done

file.close();
Quote:Original post by EasilyConfused
#include <string>#include <fstream>void f(){    std::ifstream is("whatever.dat");    std::string s;    int noob;    is >> s >> noob;}


Thanks!
------------------------------Trust me, I do this all the time.
int num;
std::string text;

file >> text >> num;


the >> operator will read in a string from the file, which is "NOOB:", and then the >> operator will read in an integer and store it in num.

EDIT: you asked for explanation then took it back! :P
Quote:Original post by Nvii
also, should close the file when your done

file.close();


You don't need to do this as the destructor for fstream objects closes files automatically.

C++: A Dialog | C++0x Features: Part1 (lambdas, auto, static_assert) , Part 2 (rvalue references) , Part 3 (decltype) | Write Games | Fix Your Timestep!

Btw, if the .dat thing is throwing you off.. you could name it .txt, .lol, .iamsocool, .wooooooo or anything you'd like. We'll, I'm sure there are some limits/exceptionms, but you get what I'm saying.

This topic is closed to new replies.

Advertisement