Wednesday, July 14, 2010

File IO

Here is the file input and output stuff. I will post a script for loops and if then statements later

IOStuff.cpp

#include <iostream>
#include <fstream>//for file stream
#include <string>
#include <cstdlib>

using namespace std;

void WriteFile();
void ReadFile();

int main()
{
WriteFile();
ReadFile();
char c;
cin >> c;

}

void WriteFile()
{
/* ofstream outFile;
outFile.open("C:\\users\\ItStudent\\desktop\\stuff.txt");*/

fstream outFile("C:\\users\\ItStudent\\desktop\\stuff.txt",
ios::out | ios::app);

cout << "How many items do you want to enter?" << endl;
int items;
cin >> items;
cin.get(); //
for(int i=1;i<=items;i++)
{
cout << "Enter the item name" << endl;
char line[100];
cin.getline(line, 100);
outFile << line << "\t";
//cin.get();
cout << "Enter the price" << endl;
double price=0;
cin >> price;

outFile << price << endl;
cin.get();
}

outFile.close();
}

void ReadFile()
{
// ifstream inFile();
//inFile.open("C:\\users\\ItStudent\\desktop\\stuff.txt");
fstream inFile("C:\\users\\ItStudent\\desktop\\stuff.txt",
ios::in);
string line;

if (inFile.is_open())
{
while(!inFile.eof())
{
getline(inFile,line);
cout << line << endl;
}
inFile.close();
}
else
{
cout << "Could not open the file" << endl;
}

}

No comments:

Post a Comment