C++ 文件I/O操作-奇怪字符输入?
我在下面的程序中使用C++ 文件I/O操作-奇怪字符输入?,c++,file-io,fstream,c-strings,C++,File Io,Fstream,C Strings,我在下面的程序中使用str.erase()函数来擦除输出的某些部分。但最后我得到了一个奇怪的输出,像这样���� 我的文件的内容是文件的当前名称=ABCD-1234 这是我的密码: #include <iostream> #include <fstream> #include <string> #include <stdio.h> #include <stdlib.h> using namespace std; //std::ifst
str.erase()
函数来擦除输出的某些部分。但最后我得到了一个奇怪的输出,像这样����代码>
我的文件的内容是文件的当前名称=ABCD-1234
这是我的密码:
#include <iostream>
#include <fstream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
//std::ifstream;
int main ()
{
string line;
ifstream myfile ("/home/highlander141/NetBeansProjects/erase_remove/dist/Debug/GNU-Linux-x86/abc.txt");
if (myfile.is_open())
{
while ( !myfile.eof() ) //myfile.good()
{
getline (myfile,line);
//line = myfile.get();
//if(!myfile.eof())
cout << line <<endl;
std::string str (line);
str.erase (str.begin()+0, str.end()-9);
std::cout << str << endl;
}
myfile.close();
//remove("/home/highlander141/NetBeansProjects/erase_remove/dist/Debug/GNU-Linux-x86/abc.txt");
}
else cout << "Unable to open file";
return 0;
}
在读取输入之前,您正在检查eof()
。按如下方式修改循环:
while ( 1 )
{
getline (myfile,line);
if ( myfile.eof() )
break;
// Rest of the loop
}
你能给我看一下真正的代码吗<代码>行
未在任何地方声明。@JesseGood请立即检查修改后的代码……您没有检查getline
中的返回值,这样使用eof
是不正确的。您也不检查行的长度是否足以使str.end()-9
有效。为什么不while(getline(myfile,line))
?检查eof
很少是正确的处理方法。
while ( 1 )
{
getline (myfile,line);
if ( myfile.eof() )
break;
// Rest of the loop
}