我有 2 个文件处理问题。
- 文件 (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/