Page 1 of 1 [ 3 posts ] 

Albinoboy
Yellow-bellied Woodpecker
Yellow-bellied Woodpecker

User avatar

Joined: 5 Aug 2010
Age: 28
Gender: Male
Posts: 70
Location: Surrey, England

22 Aug 2010, 2:20 pm

Hiya.
I want C++ to output the contents of a text file.
The text file is like this:

Quote:
Bugs Bunny, Daffy Duck, Tree House
Steve Jobs, Bill Gates, Boardroom

And I want my C++ (CUI app) to display it like this:
[tt]Name | Friend | Place
-----------|------------|------------
Bugs Bunny | Daffy Duck | Tree House
Steve Jobs | Bill Gates | Boardroom[/tt]
Obviously the two top lines can be done with C Out, but its the actual file that I can't do.

P.s. I'm new to C++!
P.s.s. I'm using Windows, Visual C++ 2010.
And on a random note: Bill Gates and Steve Jobs together = Street fight! :P Get your cameras!



Jaydog1212
Toucan
Toucan

User avatar

Joined: 8 Jan 2009
Age: 42
Gender: Male
Posts: 257

22 Aug 2010, 4:48 pm

Learn C++ in 21 Days is a good starting point:
Click here: Learn C++ in 21 Days

Quote:
#include <fstream.h>
2: int main()
3: {
4: char fileName[80];
5: char buffer[255]; // for user input
6: cout << "File name: ";
7: cin >> fileName;
8:
9: ofstream fout(fileName); // open for writing
10: fout << "This line written directly to the file...\n";
11: cout << "Enter text for the file: ";
12: cin.ignore(1,'\n'); // eat the newline after the file name
13: cin.getline(buffer,255); // get the user's input
14: fout << buffer << "\n"; // and write it to the file
15: fout.close(); // close the file, ready for reopen
16:
17: ifstream fin(fileName); // reopen for reading
18: cout << "Here's the contents of the file:\n";
19: char ch;
20: while (fin.get(ch))
21: cout << ch;
22:
23: cout << "\n***End of file contents.***\n";
24:
25: fin.close(); // always pays to be tidy
26: return 0;
27: }

Output: File name: test1
Enter text for the file: This text is written to the file!
Here's the contents of the file:
This line written directly to the file...
This text is written to the file!

***End of file contents.***


In CS classes and math classes in general, nothing made sense until I went home and tried things. I would work through the above PDF sequentially and do the exercises. What really helped me is to "step into" a program and cout variables to see what was going on......

I think you can do a character array (see above) or define your sentences as a string but I don't remember.



Albinoboy
Yellow-bellied Woodpecker
Yellow-bellied Woodpecker

User avatar

Joined: 5 Aug 2010
Age: 28
Gender: Male
Posts: 70
Location: Surrey, England

22 Aug 2010, 7:00 pm

thx! You a real help!
Now I just need to work out how to separate the contents into variables...
Or I could go low tech and do it all via the text file...