I am currently having problems with my getline in main. Whenever I use it, it prints out the last word in my input file twice. I do not know how to get rid of it. Any help is appreciated.

Input file:

noon
dog
race car
cat
mom
bob


Current Output:

noon is a palindrome.
dog is a palindrome.
race car is not a palindrome.
cat is a palindrome.
mom is a palindrome.
bobbob is a palindrome.


Expected Output:

noon is a palindrome.
dog is a palindrome.
race car is not a palindrome.
cat is a palindrome.
mom is a palindrome.
bob is a palindrome.

Full Program

#include <fstream>
#include <string>

using namespace std;

bool Palindrome (string pal, int index, int length, ofstream& outData);


int main() 
{
    
    string words;
    
    
    ifstream inData("input.txt");
    ofstream outData("output.txt"); 
    
    while (inData>>words)
   {
    outData<<words;
    getline(inData,words);                 
    Palindrome(words, 0, words.length(),outData);
   }
    
     inData.close();
     outData.close();
     

   system("PAUSE");
   return 0;

}




bool Palindrome (string pal, int index, int length, ofstream& outData)
{

      
if ((length == 0 || length == 1))
  {
            
 outData << pal << " is a palindrome." << endl;

   return true;
  }

if ( pal[index] == pal[length - 1] )
   return Palindrome(pal,index+1,length-1,outData);


else
  {
  outData << pal << " is not a palindrome." << endl;
   return false;
   }


}

Edited 7 Years Ago by NinjaLink: n/a

Why are you doing two input actions in the loop?
The first, in the while condition, reads the word and stops at the newline. The getline will read and discard the newline, storing an empty string to your variable.

The doubled up bob is being caused by your not putting a newline after bob in the data file. Good files end with a newline. In fact, bob is the only word being sent to the palindrome function, so you see it twice - when you display it after reading and when the function displays its result.

I would put the getline statement in the while condition, and leave it at that.

while ( getline( inData, words ) )
	{
		Palindrome( words, 0, words.length(),outData );
	}

A few times I attempted to put getline in the while loop, but I put it incorrectly. Thanks for showing me that it is possible to do that. I have learned something. Problem Solved.

This question has already been answered. Start a new discussion instead.