473,908 Members | 5,120 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

cin.clear() does not work

AD
Hi

I am trying to read elements of a vector from console (cin) in two
steps ie, read a list of numbers from cin. Sort these. Then read from
cin again and append in same vector.

/*************** *************** *************** *************** *****/
#include<iostre am>
#include<algori thm>
#include<vector >
#include<iterat or>

using namespace std;

int main()
{

ios_base::iosta te ios = cin.exceptions( );
cin.exceptions( ios_base::eofbi t|ios_base::fai lbit|ios_base:: badbit);

vector<int> v1;

try
{
cout<<"Enter first List:";

//read first time
copy(istream_it erator<int>(cin ), istream_iterato r<int>(),
back_inserter(v 1));
//I enter some integers followed by either some non-integer or
ctrl-D & Enter to
//signify end of stream
}
catch(ios_base: :failure)
{
//always getting a badbit exception even if I enter Ctrl-D
//which I thought signified eof

ios_base::iosta te s = cin.exceptions( );

if(s&ios_base:: badbit) cout<<"\n BadBit Exception";
else if(s&ios_base:: failbit) cout<<"\n Fail Bit Exception";
else if(s&ios_base:: eofbit) cout<<"\n EOF Bit Exception";
}

try
{
//clear cin state
cin.clear(); //cin.clear(ios_b ase::badbit) causes BadBit exception

//sort input array
sort(v1.begin() , v1.end());

cout<<"\nEnter Second List:";

//read second time
copy(istream_it erator<int>(cin ), istream_iterato r<int>(),
back_inserter(v 1));
}
catch(ios_base: :failure)
{
ios_base::iosta te s = cin.exceptions( );
if(s&ios_base:: badbit) cout<<"\n BadBit Exception";
else if(s&ios_base:: failbit) cout<<"\n Fail Bit Exception";
else if(s&ios_base:: eofbit) cout<<"\n EOF Bit Exception";
}

return 0;
}//endmain()
/*************** *************** *************** *************** *****/

First Time I enter some integers and then a character or ENTER & Ctrl-D
(which should work as EOF). I get a badbit exception (surprisingly even
in case of Ctrl-D I am getting bad bit and not eof) which I clear by
invoking cin.clear(). Now when I try to input elements from cin again
(second time) , I get badbit exception immediately (without taking any
input)..:-(

Seemingly either cin.clear() is not resetting bad bit or bad bit has to
be handled differently.
I even tried cin.clear(ios_b ase::badbit) but that causes an exception
at that point itself.

How can I read cin further once it gets corrupted due to bad input?

I am compiling it on Windows with g++ compiler.

thanks & regds
AD

Mar 25 '06 #1
1 6234
In article <11************ *********@g10g2 000cwb.googlegr oups.com>,
"AD" <an************ *@gmail.com> wrote:
Hi

I am trying to read elements of a vector from console (cin) in two
steps ie, read a list of numbers from cin. Sort these. Then read from
cin again and append in same vector.

/*************** *************** *************** *************** *****/
#include<iostre am>
#include<algori thm>
#include<vector >
#include<iterat or>

using namespace std;

int main()
{

ios_base::iosta te ios = cin.exceptions( );
cin.exceptions( ios_base::eofbi t|ios_base::fai lbit|ios_base:: badbit);

vector<int> v1;

try
{
cout<<"Enter first List:";

//read first time
copy(istream_it erator<int>(cin ), istream_iterato r<int>(),
back_inserter(v 1));
//I enter some integers followed by either some non-integer or
ctrl-D & Enter to
//signify end of stream
}
catch(ios_base: :failure)
{
//always getting a badbit exception even if I enter Ctrl-D
//which I thought signified eof

ios_base::iosta te s = cin.exceptions( );

if(s&ios_base:: badbit) cout<<"\n BadBit Exception";
else if(s&ios_base:: failbit) cout<<"\n Fail Bit Exception";
else if(s&ios_base:: eofbit) cout<<"\n EOF Bit Exception";
}

try
{
//clear cin state
cin.clear(); //cin.clear(ios_b ase::badbit) causes BadBit exception

//sort input array
sort(v1.begin() , v1.end());

cout<<"\nEnter Second List:";

//read second time
copy(istream_it erator<int>(cin ), istream_iterato r<int>(),
back_inserter(v 1));
}
catch(ios_base: :failure)
{
ios_base::iosta te s = cin.exceptions( );
if(s&ios_base:: badbit) cout<<"\n BadBit Exception";
else if(s&ios_base:: failbit) cout<<"\n Fail Bit Exception";
else if(s&ios_base:: eofbit) cout<<"\n EOF Bit Exception";
}

return 0;
}//endmain()
/*************** *************** *************** *************** *****/

First Time I enter some integers and then a character or ENTER & Ctrl-D
(which should work as EOF). I get a badbit exception (surprisingly even
in case of Ctrl-D I am getting bad bit and not eof) which I clear by
invoking cin.clear(). Now when I try to input elements from cin again
(second time) , I get badbit exception immediately (without taking any
input)..:-(

Seemingly either cin.clear() is not resetting bad bit or bad bit has to
be handled differently.


Clear is resetting the bad bit but the character or cntrl-D is still in
the stream. So as soon as you start trying to read the second time, you
get another exception when it tries to once again read the bad data.

Try adding this after the clear:

cin.ignore( numeric_limits< streamsize>::ma x() );

--
Magic depends on tradition and belief. It does not welcome observation,
nor does it profit by experiment. On the other hand, science is based
on experience; it is open to correction by observation and experiment.
Mar 26 '06 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
34044
by: TaiwanNoWhere | last post by:
// case 1 int Option = 0; for(;;) { cin >> Option; switch(Option) { case 1:
3
11161
by: Kyle Kolander | last post by:
I posted this in response to a previous thread but have not gotten any replies back... Hopefully someone has an answer? From looking at sections 27.7.3.2 and 27.7.1.2 of the standard, it appears str("") does not clear the stream bits. It seems to me that in clearing the internal buffer, one would intend that the stream bits would also be reset (in a good state). Is there a reason this is not the defined behavior? Aside from a slight...
22
4258
by: mp | last post by:
i have a python program which attempts to call 'cls' but fails: sh: line 1: cls: command not found i tried creating an alias from cls to clear in .profile, .cshrc, and /etc/profile, but none of these options seem to work. my conclusion is that a python program that is executing does not use the shell (because it does not recognize shell aliases). is this correct?
9
9214
by: Àî°× | last post by:
hi all: I want erase a stringstream' content for input new data to it. example: std::stringstream stm; stm<<"this is a string"; std::cout<<stm.str(); // here print:this is a string
9
5052
by: silversurfer | last post by:
Hello world, I was just wondering why the clear-line in my Makefile does not work: main:main.o $(ADDOBJS) clear @g++ -o main $(LDFLAGS) $+ As far as I understood it, it should be possible to add multiple shell-commands.. Nevertheless, this does compile the files, but the 'clear' before does not work..
0
1189
by: dpierson | last post by:
I have just converted one of my applications from .Net 1.1 / VS2003 to ..Net 2.0 / VS2005. I'm now seeing some different behavior in my app. Here's a simple case description: Form 1: Stock form with MainMenu and one MenuItem (menuItem1) which has several sub-MenuItems of its own. IsMdiContainer = true. Has a button (button1).
5
18361
by: madhu | last post by:
http://msdn2.microsoft.com/en-us/library/fs5a18ce(VS.80).aspx vector <intv1; v1.push_back( 10 ); //adds 10 to the tail v1.push_back( 20 ); //adds 20 to the tail cout << "The size of v1 is " << v1.size( ) << endl; v1.clear( ); //clears the vector I have a few questions:
4
2351
by: shapper | last post by:
Hello, Consider the following design: <div id="container"> <div id="A" class="A"></div> <div id="B" class="B"></div> </div> And the CSS classes:
9
3767
by: Jess | last post by:
Hello, I tried to clear a vector "v" using "v.clear()". If "v" contains those objects that are non-built-in (e.g. string), then "clear()" can indeed remove all contents. However, if "v" contains built-in types (e.g. int), then "clear()" doesn't remove anything at all. Why does "clear()" have this behaviour? Also, when I copy one vector "v1" from another vector "v2", with "v1" longer than "v2" (e.g. "v1" has 2 elements and "v2" has...
0
10035
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9876
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10915
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
11044
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9723
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5933
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
6137
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4772
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3357
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.