Using text file data in c++

I want to display data that is in text file and than use it in my c++ code
The problem in my code is it shows empty screen when i try to display it
The format of text file is :
ID : 1
NAME : s
ID :
//and so on

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
void Traverse(Tree *temp)
	{
string ID="ID :";
string NAME="NAME :";
string name;
int id;
ifstream fin;
fin.open("Data1.txt",ios::out|ios::app,ios::in);
	while (!fin.eof())
	{
		fin>>ID>>id;
		fin>>NAME>>name;
	}
	if (temp!=NULL)
		{

			Traverse(temp->Left);
			std::cout<<"ID :"<<temp->data<<endl;
		/*	fin>>"ID : ">>temp->data;*/
			std::cout<<"NAME :"<<temp->name<<endl;
			/*fin<<"NAME :"<<temp->name<<endl;*/
			Traverse(temp->Right);
		}
	fin.close();
    }
closed account (j3Rz8vqX)
Are you reading from file, or writing to file?
ifstream: Stream class to read from files
http://www.cplusplus.com/doc/tutorial/files/

What you had: ifstream fin;//Your provided code will be reading?
If both: fstream fin;//Using both I/O

If you're reading, an approach would be: fin.open("Data1.txt",ios::in);
If you're writing: fin.open("Data1.txt",ios::out|ios::app);
If BOTH: fin.open("Data1.txt",ios::out|ios::app|ios::in);


For writing, use <<
For reading, use >>
Refer to the above link.

Possible reading example:
1
2
3
4
5
6
    while (!fin.eof())
    {
        fin>>id;            //I will be on erased the next iteration. Back me up!!!
        fin>>name;          //I will be on erased the next iteration. Back me up!!!
        cout<<ID<<id<<NAME<<name<<endl;
    }

Possible writing_to_file example:fin<<id<<'\n'<<name<<'\n';

Edit:
If your data was delimited by newlines, you could use something like this:
1
2
3
    getline(fin,id);
    getline(fin,name);
    cout<<ID<<id<<NAME<<name<<endl;
Last edited on
Writing with method w
1
2
3
4
5
hile (!fin.eof())
    {
        fin>>id;            //I will be on erased the next iteration. Back me up!!!
        fin>>name;          //I will be on erased the next iteration. Back me up!!!
        cout<<ID<<id<<NAME<<name<<endl;

}
gives me an error MSB6006"link.exe" exited with code-1073741502
m calling show from another function
After writing it in main it gives me garbage value in output
Last edited on
There's a space before and after the colons?

Then maybe something like this should work xD:
1
2
3
4
5
6
7
8
9
std::string tmp; // For the "ID" and "NAME" parts, which we don't need
int id;
std::string name;
std::ifstream fin("Data1.txt");
while (std::getline(((fin >> tmp >> std::ws).ignore() >> id >> tmp >> std::ws).ignore() >> std::ws, name))
{
    std::cout << "ID = " << id;
    std::cout << "Name = " << name << '\n';
}
:D thank you it works but i don't understand how
Topic archived. No new replies allowed.