首页 > 解决方案 > C++ 如果我 Endl,它会在文件末尾捕获字符“\n”,如果我不写 endl,它会捕获最后一个字符两次

问题描述

你好我正在尝试编写一个 C++ 程序,它从文件中读取字符串并检查它是否是回文,使用文件处理来改进我的文件处理概念。但它不能正常工作我面临的问题是 file << palindrome; 如果字符串回文是 AKKA 并且我将它写在文件中。 在阅读它时会显示“akkaa” ,如果我尝试使用 endl 来创建下一行。 file << palindrome<<endl;

它显示为“akka\n\n” ,所以有人告诉我使用 .fail() 而不是 EOF,但我想在循环结束时结束循环,而不是在它无法读取下一行时我尝试在线搜索这个问题但没有得不到满意的答案

完整代码如下:

#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;
}

标签: c++file-handling

解决方案


推荐阅读