LinuxQuestions.org
View the Most Wanted LQ Wiki articles.
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices

Reply
 
Search this Thread
Old 03-27-2007, 06:36 AM   #1
entz
Member
 
Registered: Mar 2007
Location: Milky Way , Planet Earth!
Distribution: Opensuse
Posts: 453
Blog Entries: 3

Rep: Reputation: 40
Catch 22 at cin


Greetings fellow coders,

Did anybody compile a code like this one ?
Code:
#include<iostream>
using namespace std;

int main(){
	char x[10];
	for(;;){
		cout<<"Enter Message:";
		cin.getline(x,10);
		cin.clear();
		cout<<"Message is:"<<x<<endl;
	}
	return 0;	
}
If you have done this before , then you'd probably know what I'm going to refer to .
to the point , code runs fine but when more than the number of bytes specified in getline()
get inserted by the user , then some weird behaviour start to rise from the program (which ranges from the code entering an infinite loop to the program re-printing the rest chars , basically that varies from Os to another , If my memory serves me right)

so the question is , does anybody know a cure to this?
I suppose it has to be some very simple funcation call from the cin class or something in order to clear the cin stream..etc
so far I've experimented alot but since I'm no longer wanting to try random function calls , I did post this thread to find a quick remedy to this "Crisis"

comments appreciated

and thanks
 
Old 03-27-2007, 08:58 AM   #2
xhi
Senior Member
 
Registered: Mar 2005
Location: USA::Pennsylvania
Distribution: Slackware
Posts: 1,065

Rep: Reputation: 45
> which ranges from the code entering an infinite loop ...

eh, thats because it is an infinite loop
 
Old 03-27-2007, 12:24 PM   #3
entz
Member
 
Registered: Mar 2007
Location: Milky Way , Planet Earth!
Distribution: Opensuse
Posts: 453
Blog Entries: 3

Original Poster
Rep: Reputation: 40
you didn't get what I mean

I was talking about entering into an un-responsive infinite loop , which shouldn't happen at all , since the cin.getline should halt execution until the user inserts something and presses the return button (that usually occurs when clear() is not used )

but even if cin.clear() is used then , an error still takes place where the cin.getline function automatically returns with rest chars that weren't copied to the string in the last iteration.
Just compile the code and have a look yourself!

so the question remains how to resolve this issue?

and thanks
 
Old 03-27-2007, 01:09 PM   #4
dmail
Member
 
Registered: Oct 2005
Posts: 970

Rep: Reputation: Disabled
Quote:
Originally Posted by entz
I was talking about entering into an un-responsive infinite loop , which shouldn't happen at all , since the cin.getline should halt execution until the user inserts something and presses the return button (that usually occurs when clear() is not used )

but even if cin.clear() is used then , an error still takes place where the cin.getline function automatically returns with rest chars that weren't copied to the string in the last iteration.
Just compile the code and have a look yourself!

so the question remains how to resolve this issue?

and thanks
I don't see an issue, it is behaving as it should.
Code:
int main(int argc, char *argv[])
{
	using namespace std;
	char x[10];
	for(;;)
	{
		cout<<"Enter Message:";
		cin.getline(x,10);
		if(cin.fail())
		{
			if(cin.bad())
			{
				cout <<"all bets are off, cin is in a bad state"<<endl;
			}
			else
			{
				cout <<"stream has failed but not currupt, although input may have been lost" <<endl;
			}
			cin.clear();
		}
		cout<<"Message is:"<<x<<endl;
	}
	return 0;
}

Last edited by dmail; 03-27-2007 at 01:10 PM.
 
Old 03-27-2007, 01:22 PM   #5
xhi
Senior Member
 
Registered: Mar 2005
Location: USA::Pennsylvania
Distribution: Slackware
Posts: 1,065

Rep: Reputation: 45
> but even if cin.clear() is used then , an error still takes place where the cin.getline function automatically returns with rest chars that weren't copied to the string in the last iteration.

sure thats an error, but its an error in your expectations. if you do not want those other chars, you need to write something that reads the rest of the unwanted data from stdin..

(hint. just loop discarding chars until it is empty)
 
Old 03-27-2007, 02:25 PM   #6
entz
Member
 
Registered: Mar 2007
Location: Milky Way , Planet Earth!
Distribution: Opensuse
Posts: 453
Blog Entries: 3

Original Poster
Rep: Reputation: 40
Wink this brings us a step further

@dmail:
OK , now by checking cin.fail we can detect if the user entered more than he have should , but the core
problem is still evident
what I was thinking , is that cin class/stream must have a pointer/indexer or something that tells
how many bytes are in the input buffer.
without this integer cin wouldn't have a clue how many bytes it should copy to the char array , therefore it has to be there.
now what should be done is call a function from the class cin that fullfils the task of reseting this indexer to zero , this way no problem should arise no matter how long the input was.
or if the buffer is null terminated then the function should set the Null on the first char ..etc
i thought that cin.clear would do this but apparently it doesn't do what it's supposed to (i.e clearing)

Quote:
hint. just loop discarding chars until it is empty
thanks for notice but I guess that cpu cycles are too precious to waste them on such trivial tasks , there has to be a "smarter" way to fix it.

again your attention is required , thanks
 
Old 03-27-2007, 03:08 PM   #7
dmail
Member
 
Registered: Oct 2005
Posts: 970

Rep: Reputation: Disabled
Quote:
but the core problem is still evident
Hmmm what problem?
Quote:
I thought that cin.clear would do this but apparently it doesn't do what it's supposed to (i.e clearing)
R I see the problem, do you want me to tell you?
/me bites his tongue.
Have a look at ignore, gcount ...

Quote:
I'm no longer wanting to try random function calls
I would suggest you buy yourself a good book, depending on how much you know you may want to look at stroustrup, a quick search of these forums should show up a number of threads with book recommendations in.

Last edited by dmail; 03-27-2007 at 03:24 PM.
 
Old 03-27-2007, 03:28 PM   #8
xhi
Senior Member
 
Registered: Mar 2005
Location: USA::Pennsylvania
Distribution: Slackware
Posts: 1,065

Rep: Reputation: 45
> i thought that cin.clear would do this but apparently it doesn't do what it's supposed to (i.e clearing)

perhaps you should take a look at some documentation instead of assuming what functions do.
 
Old 03-27-2007, 03:35 PM   #9
xhi
Senior Member
 
Registered: Mar 2005
Location: USA::Pennsylvania
Distribution: Slackware
Posts: 1,065

Rep: Reputation: 45
> there has to be a "smarter" way to fix it.

when you come up with one i would be interested in seeing it.
 
Old 03-27-2007, 03:40 PM   #10
entz
Member
 
Registered: Mar 2007
Location: Milky Way , Planet Earth!
Distribution: Opensuse
Posts: 453
Blog Entries: 3

Original Poster
Rep: Reputation: 40
alright then

OK folks , you could have been honest from the start and told me that you don't a have a clue as myself , nobody is perfect there is no shame to say : "I dunnu know" (instead of telling me to read books and/or giving psuedo solutions )

but at last I just want to say , that you have been a tremendous (...not) Help in this regard .
thank you all for the "constructive" contribution !

*giggles*
 
Old 03-27-2007, 03:45 PM   #11
dmail
Member
 
Registered: Oct 2005
Posts: 970

Rep: Reputation: Disabled
Quote:
Originally Posted by entz
OK folks , you could have been honest from the start and told me that you don't a have a clue as myself , nobody is perfect there is no shame to say : "I dunnu know" (instead of telling me to read books and/or giving psuedo solutions )

but at last I just want to say , that you have been a tremendous (...not) Help in this regard .
thank you all for the "constructive" contribution !

*giggles*
Sometimes on forums comedy does not shine through! I do hope that was a joke.
You have not shown a problem and I have found it hard to understand what you think is the problem. The reason I suggested you buy a book is that it is the best method of learning a language.
Correct there is no shame in not knowing an answer but then if you search the forum you will find myself normally saying "I think" or "As far as I know", or being proved completely an utterly incorrect at which point I admit it.

Last edited by dmail; 03-27-2007 at 03:50 PM.
 
Old 03-27-2007, 03:45 PM   #12
xhi
Senior Member
 
Registered: Mar 2005
Location: USA::Pennsylvania
Distribution: Slackware
Posts: 1,065

Rep: Reputation: 45
i already gave you a portable solution that is commonly used.

assume yourself some new answers if you dont like the ones you get

> I thought that cin.clear would do this but apparently it doesn't do what it's supposed to (i.e clearing)
i assume this function does X.. it does Y, so that function must be wrong.

(i would venture a guess that the giggles you hear are directed at you)

Last edited by xhi; 03-27-2007 at 03:47 PM.
 
Old 03-27-2007, 11:40 PM   #13
graemef
Senior Member
 
Registered: Nov 2005
Location: Hanoi
Distribution: Fedora 13, Ubuntu 10.04
Posts: 2,379

Rep: Reputation: 148Reputation: 148
you want a smarter way?
Use strings...

string x;
...
cin >> x;
 
Old 03-28-2007, 03:21 AM   #14
entz
Member
 
Registered: Mar 2007
Location: Milky Way , Planet Earth!
Distribution: Opensuse
Posts: 453
Blog Entries: 3

Original Poster
Rep: Reputation: 40
putting the comedy aside , let's get to the deal

Quote:
Originally Posted by dmail
You have not shown a problem and I have found it hard to understand what you think is the problem.
You are not seeing the problem??
OK , then plz allow me to give you a step by step guide in order to put a big marker under the error that happens:
1) the code enters the loop
2) execution stops until the user types something and hits enter
3) the char array is printed on the standard output using cout
4) code re-enters the loop...
5) Here : cin returns automatically with the remaining chars from the last iteration big big problem
looping continues until all chars are printed out of the stream.

in other words , the code is supposed to discard (i.e neglect , trash , dispose , forget ,etc) the leftover chars from the previous cycle!
but since this code is NOT doing what it's supposed to , we have a problem!
Was my explanation good enough or should I.....use a bigger marker , your C++ Excellency ?!

Last edited by entz; 03-28-2007 at 03:32 AM.
 
Old 03-28-2007, 04:10 AM   #15
graemef
Senior Member
 
Registered: Nov 2005
Location: Hanoi
Distribution: Fedora 13, Ubuntu 10.04
Posts: 2,379

Rep: Reputation: 148Reputation: 148
The getline function works in a particular way that is: read in the data from the input stream until all the data has been read. The data is read in using blocks of size bytes. If you want your program to only read in one block and ignore the rest then you must tell the stream to ignore the rest of the data.

An important part of programming is to clearly define the problem. Now that we know what you want to achieve a solution can be presented. Using in the main advice from dmail and xhi you could of achieved the following:
Code:
#include <iostream>

using namespace std;

int main()
{
   char x[10];
   for(;;){
      cout<<"Enter Message:";
      cin.getline(x,10);
      cin.clear();
      cout << cin.gcount() << " Characters read\n";
      cout<<"Message is:"<<x<<endl;
      std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
      cout << cin.gcount() << " Characters ignored\n";
   }
   return 0;	
}
You can certainly use the cin.gcount() in a smarter way. Using the cin.fail() and cin.bad() would also be an improvement.

Last edited by graemef; 03-28-2007 at 04:12 AM.
 
  


Reply

Tags
getline, ignore


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
C++::std::cin adilturbo Programming 3 07-03-2006 11:22 AM
How to cin >> string? kornerr Programming 2 11-01-2005 03:58 AM
cin.ignore Xiangbuilder Programming 4 10-08-2003 07:57 PM
g++ and cin.getline() codeviking Programming 8 07-03-2003 07:42 AM
cin.getline adam_boz Programming 6 10-02-2002 08:57 AM


All times are GMT -5. The time now is 05:49 PM.

Main Menu
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
identi.ca: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration