Brainstorm question

C++ Automatic File Read

Page 1 of 1

9 Replies - 3602 Views - Last Post: 26 December 2009 - 11:53 AM Rate Topic: -----

#1 jefferymcclintock  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 13
  • Joined: 11-December 09

Brainstorm question

Post icon  Posted 25 December 2009 - 02:47 PM

I have to modify a C++ program that will process the input file automatically. I want the user to be able to provide the input file name as a command line to the C++ program. The issue that I have as I have looked at the dreamincode site is that I have been unable to grasp the tutorials on loading a file. The second issue is the problem that I have just written because as I have looked around and am really wanting an elementary learning guide to grasp the concepts. If anyone has any ideas please let me know as it would be greatly appreciated. Thank you and Merry Christmas

Is This A Good Question/Topic? 0
  • +

Replies To: Brainstorm question

#2 janotte  Icon User is offline

  • code > sword
  • member icon

Reputation: 990
  • View blog
  • Posts: 5,141
  • Joined: 28-September 06

Re: Brainstorm question

Posted 25 December 2009 - 02:53 PM

You seem to have three questions in there sort of mixed together.

Please choose the first one that you would like to look at so we can work with you one step at a time.

Would you like to look at how to read command line arguments? or how to open a file for input? or <I'm not sure what the other one exactly is>?

Attacking challenges one small piece at a time is one of the key techniques of programming.
Was This Post Helpful? 0
  • +
  • -

#3 taylorc8  Icon User is offline

  • B&

Reputation: 149
  • View blog
  • Posts: 1,572
  • Joined: 21-July 09

Re: Brainstorm question

Posted 25 December 2009 - 07:06 PM

C++ file io in a fast reply box:

ifstream infile;
infile.open("C:\\file.txt",ios::in | ios::binary);


k, now.. the first thing you're going to tell the infile object is the path to the file including the file name... If you don't include the path to the file it will look for the file in the current directory, and using visual studio 2008 can be somewhat iffy about that.

The second part, string together options for your new opened file (opened for reading) with |
like say... ios::in | ios::ate ate will set the get pointer to the end of the file. The member functions seekg() and tellg() are easy to use also! seekg() will change the location of this pointer in the file. and tellg() tells you the location. Pretty cool, right?


As for the command line.. int main(int argc,char * argv[]) is how you will be doing this! argc contains the argument count, and should always be 1 because the first element of the argv[] contains the name of your exe. So then, bring up dos, type your app name to execute it, and the argc is 1 if you only supplied the name of your application. argv[0] will contain the name of your exe complete with the .exe file extension (on windows). So now, if i type myapp.exe -p
my app has the -p argument in the argv[1] .. and argc is 2.
Savvy?

int main(int argc,char* argv[])
{
ifstream infile;
infile.open("C:\\myfile.txt",ios::in | ios::ate);
int tempFileLength=infile.tellg(); // opened at the end thus, 
//length of file !  ( you should consult a manual for a better way of doing this though)
infile.close(); // close our open file stream
return 0;
}


So now what? Well, take a good look at http://www.cplusplus...tream/ifstream/
and see what you have to work with for C++ file io with ifstream... (for getting stuff from a file, ofstream for writing to a file fstream for both)
the read() function is quite handy! http://www.cplusplus...m/istream/read/
So now, looking at the arguments and return value of read() we should be able to do:
char buffer[256];
infile.read(buffer,256);

so now our buffer would have 256 bytes of the file in it, wouldn't it? Check the location of the get pointer!
Oh no! It didn't work!

So now, let's go back to -> http://www.cplusplus.../istream/seekg/
seekg() well this look handy.

inFile.seekg(ios::beg); //this function is overloaded..  can take two arguments or one.
	inFile.read(buffer,256); //attempt to read 256 bytes of the file >:D

Well.. That appeared to work.

And our finished code is?

#include <iostream>
#include <fstream>
using namespace std;

int main(int argc, char * arv[])
{
	ifstream inFile;
	int temp=0;
	char buffer[256];
	inFile.open("C:\\test.txt",ios::in | ios::ate);  //ate = end of file.
	temp=inFile.tellg(); // location of the get pointer which is at end
	inFile.seekg(ios::beg); //this function is overloaded..  can take two arguments or one.
	inFile.read(buffer,256); //attempt to read 256 bytes of the file >:D
	cout << buffer;  // work?
	inFile.close();
	cin.get();
	return 0;
}


What I learned from this is:
http://www.cplusplus...tream/ifstream/

The internet is a good reference for all things C++. I don't know what you're needing help with, but if you're having trouble don't be afraid to check out things on the internet. I do that because I can't do my f'ing math homework.

One little update in regard to your command line stuff:
if(argc>1)
{
inFile.open(argv[1],ios::in | ios::ate);  //ate = end of file.
}


Yes my code is not good! I keep it simple for you to work out the prevention of errors in such a simple app yourself. This is the general way it works. Keep in mind though, if you run from cmd line with:
myapp.exe C:\text.txt
that \ may give you problems in your string. Just a side note. And of course if your filename has a space in it or something, do try:

myapp.exe "C:\\file name.txt"

This post has been edited by taylorc8: 25 December 2009 - 07:35 PM

Was This Post Helpful? 0
  • +
  • -

#4 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6107
  • View blog
  • Posts: 23,666
  • Joined: 23-August 08

Re: Brainstorm question

Posted 25 December 2009 - 07:22 PM

There are SO MANY file I/O tutorials, snippets and examples, not only here but all over the Internet, that I think you need to tell us what it is EXACTLY that is so confusing you, along with showing us some code that shows us where you're at. From there we may be able to point you in the right direction and give you some specific guidance, but this

Quote

am really wanting an elementary learning guide to grasp the concepts
is just. so. done. already. Specifics are in order.

Merry Christmas, and thank you so much for your service to our country!
Was This Post Helpful? 0
  • +
  • -

#5 jefferymcclintock  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 13
  • Joined: 11-December 09

Re: Brainstorm question

Posted 26 December 2009 - 08:27 AM

Okay the first issue is the inability to grasp simple input-output file
I have used this code to allow the user to submit their own file for a mortgage payment and here is the code that I have used for that.

/* 
 * File:   mortgage.cpp
 * Author: jeffery mcclintock
 *
 * Created on December 21, 2009, 1:35 PM
 */

#include <iostream>
#include <cmath>
#include <iomanip>
#include <locale>
#include <fstream>
#include <cstdlib>
#include <cstring>
#include "main.h"

using std::cout;
using std::cin;
using std::endl;



//let's get started shall we?
int main()
{
   //variables
	double iRate = 0.0;
	double eLength = 0.0;
	double ePrinciple = 0.0;

	char choice = 'Y';
	char iTest [256];
	int selection = 0;   //menu options
	int i = 0;	 //array index
	ifstream inFile;

	//let's begin the loop
	while ((choice == 'Y')||(choice == 'y'))
	{
	 cout << "This is ye olde Mortgage Calculator\n\n";
	 cout << endl;
	 cout << "Creative contributions from Jeffery McClintock\n\n";
	 cout << endl;
	 cout << "Let's get started shall we?\n\n"; cout << endl;

	 cout << "\nHow would you like to entere the amount of the loan terms?\n";
	 cout <<  "(1)  -  Enter your own information\n";
	 cout <<  "(2)   - Enter information from a file\n";
	 cout <<   "(3)  -   Not what you are looking for? (Quit)\n";

	 cin >> iTest;
	 selection = atoi (iTest);

	 while ( selection <=0  || selection > 3 || cin.fail() )
	 {
		 cin.clear();	//clear up the stream
		 cin.ignore(1000, '\n');
		 cout << "Please enter a selection between 1 and 3. *SIGH*" << endl;
		 cin >> iTest;
		 selection = atoi (iTest);
	 }

	 if (selection == 1)
	{
   
	 cout << "Please enter the amount of loan: $";
	 cin >> ePrinciple;
	 cin >> iTest;
	 ePrinciple = atof (iTest);

	 while ( ePrinciple <= 0.0 || cin.fail())  //gets rid of the negative energy
		   {
				cin.clear();
				cin.ignore(1000, '\n');

				cout << "Got to be larger than 0." << endl;
				cin >> iTest;
				ePrinciple = atof (iTest);
		   }

	 
	 cout << "Please enter the desired interest rate of the loan: $";
	 cin >> iRate;
	 cin >> iTest;
	 iRate = atof (iTest);

	 while ( iRate <=0.0 || cin.fail())
			{
				cin.clear();
				cin.ignore(1000, '\n');

				cout << "Again, has to be bigger than zero (0)." << endl;
				cin >> iTest;
				iRate = atof (iTest);
			}

	 
	 cout << "Please enter the desired length of loan: $";
	 cin >>eLength;
	 cin >> iTest;
	 eLength = atof (iTest);

	 while (eLength <= 0.0 || cin.fail())
				{
					cin.clear();
					cin.ignore(1000, '\n');

					cout << "*SIGH* Bigger than 0" << endl;
					cin >> iTest;
					eLength = atof (iTest);
				}
	 
	 

	}
	 iRate = (iRate/100);
	 mortgage mymortgage (ePrinciple, iRate, eLength);

	 double payment = mymortgage.payment();

		//sends output to the screen
cout << endl << "The payment amount with a balance of $" << setiosflags(ios::fixed) <<setprecision(2) <<mortgage <<endl;
cout << "with an interest rate of" << iRate * 100 << "% for" << eLength << "years is $" <<payment << "a month" << endl;



	 if (selection ==2)
	 {
		 cout << "\nWhat is the name of the file you desire to use.\n";
		 cin >> filename;
		 
		double line;
		
		ifstream myfile (filename);

		 int x = 0;
			if (myfile.is_open())
				{
					while ( ! myfile.eof())
						{
							myfile >> line;
							x++;
									if (x==1)
										ePrinciple = line;

										if (x==2)
											eLength = line;

											if (x==2)
												iRate = line;
						}

					myfile.close();
				}

		   else
			{
				cout << "Can't open file";
			}
	   }

if (selection ==3)

				{
						 return 0;

				}
	 }
  }




The error message that I receive off of that (Netbeans IDE 6.7.1 on Ubuntu OS) is that 1) unable to resolve identifier ifstream 2) unable to identify setiosflags 3) unable to resolve identifier ios and setprecision. I thought that I finally have an understanding of this concept but with the error messages I realize maybe I don't/

Ok the next question deals with being able to modify this program so that it will process the input file automatically. The user should be able to provide the input file name as a command line to the C++ program. The input file should contain the loan information for any number of loans. The program will output a new file (also entered on the command line) that contains the loan information along with the calculated payment.. and I think that I have a better understanding of what it is asking now from the input that I have received in the forum BUT if anyone else knows of yet another elementary example I would appreciate it. I have been to cplusplus to look and it didn't help and I still haven't found what I am looking for here on the site. Thanks
Was This Post Helpful? 0
  • +
  • -

#6 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6107
  • View blog
  • Posts: 23,666
  • Joined: 23-August 08

Re: Brainstorm question

Posted 26 December 2009 - 08:43 AM

ifstream is in the std namespace. As a beginner, I would argue that you should not complicate the issue by doing this:
using std::cout;
using std::cin;
using std::endl;


just pull in the entire std namespace using
using namespace std;


More info on namespaces for further reading.

Partition your tasks into small manageable pieces.

Quote

The user should be able to provide the input file name as a command line to the C++ program.

So there's your next task. Read an argument from the command line. Simple, eleventy billion examples available. Go do it. You need to change your main from
int main() to int main(int argc, char *argv[]). argc is the number of arguments on the command line and is always at least 1, because the first, index 0, ALWAYS contains the name of the program being run (in C/C++).
Was This Post Helpful? 0
  • +
  • -

#7 Bench  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 857
  • View blog
  • Posts: 2,343
  • Joined: 20-August 07

Re: Brainstorm question

Posted 26 December 2009 - 08:44 AM

ifstream, ios and setprecision are all part of the std namespace, so their fully-qualified names are std::ifstream, std::ios and std::setprecision.
(Try to avoid the temptation to type using namespace std;)


As for reading multiple items from a file, an ifstream works in the same way as cin. That is to say, that whatever operation you can do with cin, you can replace the name of an ifstream to do exactly the same - so you can prototype your program using cin.

eg
int num;
std::string mystring;
std::getline(std::cin,mystring);
std::cin >> mynum; 
to
std::ifstream my_fstream("file.txt");
int num;
std::string mystring;
getline(my_fstream,mystring);
my_fstream >> mynum; 


NB: When using file streams beware of the dreaded EOF flag: http://www.dreaminco...topic145699.htm

This post has been edited by Bench: 26 December 2009 - 08:45 AM

Was This Post Helpful? 0
  • +
  • -

#8 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6107
  • View blog
  • Posts: 23,666
  • Joined: 23-August 08

Re: Brainstorm question

Posted 26 December 2009 - 08:53 AM

Ah, conflicting advice...

Quote

ifstream, ios and setprecision are all part of the std namespace, so their fully-qualified names are std::ifstream, std::ios and std::setprecision.
(Try to avoid the temptation to type using namespace std;)

Bench, when you've got someone struggling with the very basics, I don't buy this advice. While I understand your motivation, I think it's counterproductive at this point.
Was This Post Helpful? 0
  • +
  • -

#9 Bench  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 857
  • View blog
  • Posts: 2,343
  • Joined: 20-August 07

Re: Brainstorm question

Posted 26 December 2009 - 09:47 AM

View PostJackOfAllTrades, on 26 Dec, 2009 - 03:53 PM, said:

Ah, conflicting advice...

Quote

ifstream, ios and setprecision are all part of the std namespace, so their fully-qualified names are std::ifstream, std::ios and std::setprecision.
(Try to avoid the temptation to type using namespace std;)

Bench, when you've got someone struggling with the very basics, I don't buy this advice. While I understand your motivation, I think it's counterproductive at this point.

I see your point, Jack - and I think most others would probably agree with you too. From my own point of view, I believe good habits are worth starting early; such as you see with books/tutors telling students to avoid global variables and public class data, but I know that I'm in a minority with that opinion.

For the OP - both ways are 'correct' in that they'll work (using namespace std is shorter/easier, its just a bit of a bad habit) - the difference for you at the moment is about style.
Was This Post Helpful? 0
  • +
  • -

#10 jefferymcclintock  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 13
  • Joined: 11-December 09

Re: Brainstorm question

Posted 26 December 2009 - 11:53 AM

the lightbulb has finally come on thanks so much bench when you used the cin example I finally understand what I need to do now and since I am ahead of schedule I am going to tweak this program a little more to what I want instead of scrambling to catch up. Thanks everyone for your time. It is greatly appreciated.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1