Sunday, July 26, 2009

How to read and store data into variables from a file in C++.?

Hello,





I need to retrieve data from a sample file and i need to store that retrieved data in to variables.





suppose i have an input file.





Input file:


1. Count=0


2. Data=4


3. Temp =5


4. Time = 30


5. choice 5





I need to store the values from the input file into variables. can any one with good knowledge of C++ can help me out.





Thank You

How to read and store data into variables from a file in C++.?
Minor modification needed, but I need to run!





#include %26lt;string%26gt;


#include %26lt;fstream%26gt;





string buffer;


int count;


int data;


int temp


int time;


int choice;





ifstream fin("file.txt");





fin %26gt;%26gt; buffer %26gt;%26gt; buffer %26gt;%26gt; count;


fin %26gt;%26gt; buffer %26gt;%26gt; buffer %26gt;%26gt; data;


fin %26gt;%26gt; buffer %26gt;%26gt; buffer %26gt;%26gt; temp;


fin %26gt;%26gt; buffer %26gt;%26gt; buffer %26gt;%26gt; time;


fin %26gt;%26gt; buffer %26gt;%26gt; buffer %26gt;%26gt; choice;
Reply:ifstream fin("test.txt");


string s;


while( getline(fin,s))


cout %26lt;%26lt; s%26lt;%26lt;endl;





you'll need to #include %26lt;ifstream%26gt;





So yeah, its really that simple.
Reply:The last answer looked OK, but this becomes REALLY challenging if you want the program to allocate the variables in the input file dynamically. Currently, I have no way of doing this.


Sorry I can't help you any more than that.


No comments:

Post a Comment