Advertisement

Using cin.get and looping

Started by February 13, 2002 06:31 PM
5 comments, last by Crazygnome 22 years, 10 months ago
I am writing a program that will take what a user enters and reverses it however I''ve been working on a problem for about an hour and have not figured it out yet. The code in question looks like this:
  

cout<<"Enter a word or phrase \n";
cin.getline(phrase, 499);

  
Now that works fine and dandy except when I loop the program over again it does not let me input another phrase nor does it even print the backwards phrase a second time. If you need more source just let me know.
I am guessing that the problem is probably in your reversing code. Things you want to make sure are that you are copying the ''\0'' to the end of the char array. As an example...

char szCommand[128];
char szCopy[128];
int count = 0;
int te;
cout << "In: ";
cin.getline(szCommand, 126);

for(int j = 0; j < 126; j++)
{
if(szCommand[j] == ''\0'') break;
count++;
}

te = count;
for(int k = 0; k < te; k++)
{
count--;
szCopy[k] = szCommand[count];


}
szCopy[te] = ''\0'';
cout << szCopy << endl;
Advertisement
I think you misunderstood. I have a do while loop that surrounds the majority of the program. The first time through everything turns out fine but if the user chooses to run it again...well thats when things look scary. Well heres the source code in its entirety. Thanks for the help
  #include <iostream.h>#include <string.h>int main(){	int answer;		int x;	int y ;	char  phrase[500];	char  newphrase[500];	do	{	    		cout<<"Enter a word or phrase \n";		cin.getline(phrase, 499);				newphrase[strlen(phrase)] = ''\0'';		x= 0;		int m = strlen(phrase);		y =(strlen(phrase) - 1); 			do		{		newphrase[y] = phrase[x];			if (phrase[x] == ''\0'') break;			x++;			y--;		}while(x < m);		newphrase[y] = ''\0'';	cout<< newphrase << "\n";		cout<<"Would you like to continue? (1 - Yes, 2 - No) :";		cin>> answer;		if(answer> 2 || answer < 1)		{			cout<<"ERROR: Invalid Answer";			answer = 1;		}		}while(answer == 1);			return 0;}  
Try using endl insead of "\n".
baumep
for msvc 6.0 stl \n == endl, endl push_back''s \n, but return in windows is \r
Try using this GetLine instead:

    #include <string>#include <cstdlib>#include <iostream>using namespace std;void GetLine(istream&, string&, char);int main(){    char   command='1';    string str_in, str_out;    int    length,index,newpos;    do    {        str_in="";        str_out="";        cout<<"Enter a word or phrase: ";        cin.GetLine(cin, str_in, '\n');        switch(command)        {        case '1':  length = str_in.length();                   newpos=length-1;                   for(index=0;index<length;index++,newpos--)                      str_out.at(index)=str_in.at(newpos);                   cout<<"The new word is:<<str_out<<endl;                   break;        default:   cout<<"Unknown command, please try again."<<endl;                                     break;        };        cout<<"Would you like to continue? (1 - Yes, 2 - No) :";        cin>>command;    }while(command!='2');    cout<<"Welcome back!"<<endl;}void GetLine(istream& instream, string& str, char sentinel){    char ch;	//temporary storage for each character read    str = "";	//holds the complete user input    do    {        instream.get(ch);	//get next character of stream        if (ch!=sentinel)	//check termination char        str += ch;		//not found, add character to str    }while(ch!=sentinel);}    


I did not test this code but it should almost work. Good luck!


Why make it simple when you can make it sooo nice and complicated?

Edited by - clabinsky on February 14, 2002 3:23:12 AM
Why make it simple when you can make it sooo nice and complicated?
Advertisement
quote: Original post by abdulla
for msvc 6.0 stl \n == endl, endl push_back''s \n, but return in windows is \r


Are you suggesting that the newline constant ''\n'' is exactly the same thing as endl? That is incorrect. Inserting endl to an output stream has the side effect of flushing the stream, which can be very inefficient when performed unnecessarily within a loop body. Crazygnome already has implicit flushes in his code (the output stream is implicitly flushed when requesting input), so I don''t see a need for any explicit flushes.

Crazygnome: there are a few things you should be aware of in your code. Following the call to "cin>> answer;", an integer will have been extracted from cin and put into the int variable answer (I''m pretty sure you know that). Consider that a user could enter a non-numeric here, which would put the stream into a fail state. I haven''t tested your program, but the results of not checking for a fail state are depend on what was previously in answer. If it was 1, then you have an infinite loop, otherwise you drop out and exit. It would be safer to check for fail using if(cin.fail()), outputting your "ERROR: Invalid Answer" message if true.

The next thing to be aware of, and I think this is where your immediate problem lies. Once you have an int held in answer, there is still some "junk" in the input buffer, which is most likely the newline that the user had to enter. That newline character will stay in the buffer until your next call to getline. That means getline will retrieve an empty line from the buffer. To resolve this, you should clear the newline from the buffer using the istream::ignore() function (look it up). Hopefully, that will do the trick.

Lastly, I wanted to point out that when writing C++, you should not use char arrays as strings, as they are subject to all sorts of problems. C++ has a class called string for the purpose. Additionally, the STL provides various algorithms, many of which can be applied to the string class. One of those algorithms is called "reverse()" (hint, hint).

If you include all these considerations in your code, you will be reaching an "industrial strength" solution. Have fun!

This topic is closed to new replies.

Advertisement