0

hello I am trying to write a C++ program that reads a string from a file and checks whether it is palindrome or not using file handling to Improve my File handling concepts. but it's not working fine the problem I am facing is file << palindrome; if string palindrome is AKKA and I write it in the file. while reading it reads "akkaa" and if I try to write using endl to create the next line. file << palindrome<<endl;

it reads "akka\n\n" so someone told me to use .fail() instead of EOF, but i want to end loop when its end, not when it fails to read next lines I tried searching online for this problem but didn't get any quite satisfying answer

Full Code is below:

#include<iostream>
#include<string>
#include<fstream>
using namespace std;
int main()
{
    
    string palindrome,s; char c;
    cout << "Enter the String: "; cin >> palindrome;
    fstream file;
    file.open("File.txt", fstream::out);
    file << palindrome << endl;
    file.close();

    file.open("file.txt",fstream::in);
    if (file.is_open())
    {
        while (!file.eof())
        {
            file.get(c);

            s += c;
        }
    }
    for (int i = 0, j = s.length(); i != j; i++, j--)
    {
        if(s[i]!=s[j])
        {
            cout << "The string is not Palindrome " << endl;
            exit(1);
        }
    }
    cout << "The string is Palindrome.";
    return 0;
}
  • You have to check if readings are successful **before** trying to use what is "read". – MikeCAT Sep 26 '20 at 02:10
  • please elaborate i didn't get it what you said – Farhan Ashraf Sep 26 '20 at 02:18
  • 1
    @FarhanAshraf: EOF isn't set until a read *fails*. So when you call `get` the final time, it fails, sets EOF, and leaves `c` unchanged. But since you don't check for EOF after the `get`, you blindly keep the value left over from last time. – ShadowRanger Sep 26 '20 at 02:27

0 Answers0