c++ - 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;
}
解决方案
推荐阅读
- sql - 当某些日期不存在时,Windows 函数按日期排序
- java - 使用 Cmake 在 Windows x64 上为 Java 构建 OpenCV
- javascript - html2canvas 并不总是正确生成图像
- c# - 调整 TableLayoutPanel 中的可用空间
- python - 无法将字符串转换为浮点数
- php - 从两个表创建树结构
- swift - Swift - 颜色在设备上出现水洗
- android - ndk-build 没有制定目标的规则
- python - 使用 python zeep 使用 web 服务。如何处理这种响应?
- node.js - AWS S3 按名称查找文件