0
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
And another. Run the following code, entering "go 4 expert" when prompted for a string. What is the output? Did you expect that output?
Code:
int _tmain(int argc, _TCHAR* argv[])
{
	string t;
	cout<<"enter string"<<endl;
	while(cin>>t)
	{
		cout << "cin>>t gives t the value: " << t << endl;
	}
	return 0;
}
(OK, that's it for now)
0
thekevin07's Avatar, Join Date: Sep 2008
Go4Expert Member
That will print and its what i expected that was part a of the program

Code:
"go
4
expert"

i tried

Code:
			if(n==pos)
			{	
				len=1;
				pos=0;
			}
				
			
			else if(n==string::npos)
				len=t.size()-pos;
			
			else
			{
				pos += s.size();
				len=n-pos;
			}
but it created an infinite loop so i think pos needs to be 4 now but i have no clue how to do it. We've spent along time on this and I learn better by example any way Please, Please tell what i need to do to fix it (and why otherwise it's pointless). I've used this forum to help with c++ stuff that I dont understand once someone told me what to do and why I understood it better and as a result I Aced my midterm. Thanks for your patience.

Last edited by thekevin07; 7Nov2008 at 07:21..
0
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
OK. But you have to wean yourself off solving problems by getting examples from somewhere. This is not always going to be possible.

On second thoughts I'll try just once more. If you don't get it after this I'll deliver you the solution. I do understand your frustrations, I've been there; I remember debugging for two solid weeks once and finding the problem was a missing semicolon or something daft.

The outer while loop reads strings from the user and breaks them up by spaces.
The inner loop loops over the resulting string, which is <"go> on the first time through, <4> on the second and <expert"> on the 3rd.
The string "4" contains one character (a '4') at [0] and a terminating null at [1]. pos loops over this string and is the index of the character you're currently interested in. Why exactly do you think this needs to be 4? t.size() is only 1, so if pos=4 then the expression pos<t.size() is going to evaluate FALSE immediately. To go into the loop pos MUST be less than t.size(). It must also be non-negative, of course. So what is the single value that satisfies that? What number is >=0 and <1?

Since pos contains the wrong value immediately before the inner while and is fine before that, I'd say the solution probably has to go...
Code:
	while(cin>>t)
	{
		// <-- ...HERE
		while(pos <t.size())
0
thekevin07's Avatar, Join Date: Sep 2008
Go4Expert Member
I'm close i put pos=0; right between the loops and that printed

Code:
"go
4
expert

still missing the second quote though.


thanks
0
thekevin07's Avatar, Join Date: Sep 2008
Go4Expert Member
nevermind i got it thanks for all your help man