Start New Discussion within our Software Development Community

How do I read two different data types from a .dat or .txt file?

For instance I have a file that is an inventory file that shows the item reference number, the item name, and the quantity available.
Example of what the file may look like:
01 Textbook 54
02 Pencils 90

How would I get the program to read both the int value and char value then writing the data from the file onto the screen using functions??

I keep getting infinite 0's on my screen when i compile.

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;

//Prototypes
void initialization();
void process ();
void eoj ();
void openIt();
void readIt();
void calculate();
void accumulate();
void writeIt();

//Declarations
ifstream inputFile;
char sName[15];
int refNum;
int qty;

void main(void)
{

	initialization();
	
	while (!inputFile.eof())    
	{
		process();
	}

	eoj();

	cout << " <---------End Of Run----------->\n";
	return;
}


void initialization()
{
	openIt();
	readIt();
}
void process ()
{
	writeIt();
	readIt();

}
void eoj ()
{
	inputFile.close();

}
void openIt()
{
	inputFile.open("c:\\inventory.txt");
	if (inputFile.fail())
		cout << "Inventory file open failed" << endl;
	return;

}
void readIt()
{
	inputFile >> refNum  >> sName >> qty;
	return;
}
void calculate()
{

}
void accumulate()
{

}
void writeIt()
{
	cout <<  refNum << sName << qty;
	return;
}

For reading data both int and char types you can use
fscanf() function, or ifstream.

Ifstream has overloaded operator >> for many types.

This article has been dead for over six months. Start a new discussion instead.