What the Tech logo
Welcome! Register for a free account (or login) > How does it work?
  1. Quickly register. It will only take 60 seconds.
  2. Start a new topic. Ask your question. Wait for an email reply.
  3. Is your system infected? Begin reading the malware removal guide.
register button
Reply to this topicStart new topic
> C++ fstreams and strings, Not the output I'm expecting
txman
post Feb 28 2009, 02:58 AM
Post #1


Authentic Member
**

Group: Authentic Member
Posts: 30
Joined: 5-July 07
Member No.: 71,221
Operating System: Windows XP Home Edition SP2



Alright, I'm teaching myself C++, and I'm stuck on recieving information from files. Here's my code.

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
int x = 0;
string out_wanker[500];
string input_wanker;
ofstream out_file ("testfile.txt");
cout<<"Give me a file stream!"<<endl;
getline(cin, input_wanker, '\n');
out_file<<input_wanker<<" "<<"zarghly";
out_file.close();
ifstream in_file ("testfile.txt");

do
{
in_file>>out_wanker[x];
cout<<out_wanker[x]<<" ";
++x;
}while (out_wanker[x] != "zarghly");

return 0;
}


Ignore the strange variable names, I'm a strange person. but what I'm trying to do is write a string and read it back in. My hope is that "zarghly" would work as a terminator for the loop. However, thats not how it's working.

Sample input.
This is a test of how to work with file streams.

Sample output.
This is a test of how to work with file streams. zarghly (followed by roughly 500 spaces and a termination message)

So why isn't my loop terminating as it should?
Go to the top of the page
 
+Quote Post
 
Start new topic
Replies
jpshortstuff
post Mar 1 2009, 09:10 AM
Post #2


SuperHelper
Group Icon

Group: Classroom Teacher
Posts: 5,616
Joined: 28-April 07
From: UK
Member No.: 69,799
Operating System: Windows XP (Professional), Windows Vista (Home Business), Windows 7 (Ultimate), Ubuntu Linux



Would it not be easier to use the eof() function as your termination condition, rather than having a random string?

What would happen if your random string was part of the file? You would terminate prematurely.

Have a look at this link, see if it helps:
http://www.cplusplus.com/doc/tutorial/files.html

Hope that helps.
Go to the top of the page
 
+Quote Post



Reply to this topicStart new topic

 

RSS Time is now: 18th March 2010 - 01:22 PM
Advertisements do not imply our endorsement of that product or service. The forum is run by volunteers who donate their time and expertise. We make every attempt to ensure that the help and advice posted is accurate and will not cause harm to your computer. However, we do not guarantee that they are accurate and they are to be used at your own risk.
Member site: Alliance of Security Analysis Professionals | UNITE Against Malware
Memory Forums | Auto Repair Forum
© Geeks to Go, Inc. | All Rights Reserved | Privacy Policy