cin.fail() with string

Dec 20, 2011 at 5:49pm
Am i correct in thinking cin can never fail when entering into a string variable?
Dec 20, 2011 at 6:00pm
Well... cin is actually an istream object. When it is used with the extraction operator to assign data into a string variable, this might fail under some horrible circumstances... like there being no memory available.
Dec 20, 2011 at 6:13pm
It might also fail if it reach EOF and there was nothing to read
Dec 20, 2011 at 6:14pm
ok thanks. Can you help with this. Am trying to create ofstream so that when a procis called for the first time it will delete contents of file but after will append. Am using bool to do this, but it is not working.

her is code:

1
2
3
4
if (newfile)
	ofstream outfile("output.txt");
	else
	ofstream outfile("output.txt",  ios_base::app);
Dec 20, 2011 at 6:19pm
1
2
3
4
5
ofstream outfile;
if (newfile)
	outfile.open("output.txt");
else
	outfile.open("output.txt",  ios_base::app);
Dec 20, 2011 at 6:20pm
Sorry but just for clarity what is the difference?
Dec 20, 2011 at 6:32pm
The difference is that you create the ofstream object inside the if statement so it will not exist outside the if statement. In my code the object is created outside the if statement so it will still exist after the if-else statement.
Dec 20, 2011 at 6:33pm
Is it because in the second your are establishing the name ofstream and then explicitly instructing to open in a certain way whereas in the first you are establishing the name and then using a default operation of open.

i.e

ofstream outfile("output.txt");

works cos it uses default operation of open when outputting.

but

ofstream outfile("output.txt", ios_base::app);

does not work because you are just naming and cannot set method of opening until you explicitly open??

Just a theory...
Dec 20, 2011 at 6:37pm
I see, i see. Your theory is much simpler. Thanks
Dec 20, 2011 at 6:41pm
No - like Peter87 said if you create the ofstream object inside the if statement it will not exist outside the if statement

Think of this:

1
2
3
4
5
6
7
8
9
if (condition)
{
    int i=10;
}
else
{
    int i=10;
}
i+=10;


The variable i is create inside the if or else statements (here specified by brackets}. It is destroyed at the end of the bracketed section and cannot be accessed out of it. So the 'i+=10' will fail.

Search google for 'life of c++ variables' for more information.
Topic archived. No new replies allowed.