I'm working with a program where the user adds a few names together with the age. After this the program will write out the content of the text file. I'm having problems seperating the names and age into different variables. I want the program to put word nr1 in char name then word nr2 in int age word nr3 in char name and so on.

The text file will look like this for example:
Andrew 45
Mark 27
Adam 38

This is my code as it looks now. Obviously the getline shouldn't be in the writng out content function since I want the line separated into 2 different variables. But thats my problem I have no idea how to do that. Any help?

#include<fstream>
#include<iostream>
#include<sstream>
#include<conio.h>
void skrivnamn(void);
void lasafil(void);
char namn[50];int antal=0;int num;
using namespace std;
int main()
{
skrivnamn( );
lasafil( );
getch();
return 0;
}

//Adding new names to text file
void skrivnamn(void)
{
ofstream outfile("data.txt",ios::app); 
cout<<"How many names do you want to add:  "; //Asks how many names to add
cin>>antal;
cin.get();   

for(int i=0;i<antal;i++)
	{
		cout<<"Enter your name"<<endl; //Enter name
		cin>>namn;
		outfile<<namn<<" ";
		cout<<"Enter your age"<<endl; //Enter age
		cin>>num;
		outfile<<num<<endl;
	}
outfile.close();
}

//Writing out the content
void lasafil(void)
{
 string name;
 ifstream fil ("data.txt");
 if (fil.is_open())
 {
	while (! fil.eof() )
		{
			getline (fil,name);
			cout << name << endl;
		}
	fil.close();
 }

 else cout << "The file cant be found or does not exist"; 

}

you can look at the getline seperator:

getline(file, line, ' ');

Separator in this case is space ' '.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.