c++ - 文件处理错误

标签 c++

我有 2 个文件处理问题。

  1. 文件 (txt) 不是使用 fstream 创建的。这是我的代码
#include<iostream>
#include<conio.h>
#include<fstream>

void main()
{char string[80];
   int len;

std::cout<<"Enter a string ";

std::cin>>string;

 len=strlen(string);

std::fstream file;

file.open("RO1.TXT",std::ios::out|std::ios::in);

for(int i=0;i<len;i++)

file.put(string[i]);

file.seekg(0);

char ch;

while(file)

{file.get(ch);

std::cout<<ch;

}
  file.close();
getch();
}

没有创建名为 RO1.TXT 的文件的问题 我的 fstream 损坏了吗?

2.如果我使用 ofstream 和 ifstream 进行构建,则正在创建文件,但会显示一个额外的字符 代码

   #include<iostream>
#include<conio.h>
#include<fstream>

void main()
{std::ofstream file;
char string[80];
int len;
file.open("RO1.TXT");

std::cout<<"Enter a string ";
std::cin>>string;
 len=strlen(string);

for(int i=0;i<len;i++)
    file.put(string[i]);
file.close();
std::ifstream file1;
file1.open("RO1.TXT");
char ch;
while(file1)
{file1.get(ch);
std::cout<<ch;
}
file1.close();
getch();
}

问题是显示了额外的字符

最佳答案

最后一个字符显示两次,因为您在读取文件之前(即读取文件结尾之前)检查文件流错误。您需要在获取字符后检查错误。

关于c++ - 文件处理错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20198370/

相关文章:

c++ - 从字符串中删除字符的第一个和最后一个实例?

c++ - 如何在 Windows 中更改系统时区?

c++ - QPainter 中的文本比 QPainterPath 中的文本好得多

c++ - 使用 cpp-httplib 的 POST 请求

c++ - 调试版本的静态库会泄露源代码信息吗?

c++ - Qt : icon messing the width of QPushButton - Adjusting icon

c++ - 如何在 C 中重现 C++ 类样式的 get 函数?

.net - 在 .NET 语言中使用 C++ header

C++ 保护进程不被挂起

c++ - wchar_t 究竟能代表什么?