gpt4 book ai didi

c++ - 文件 I/O 操作 - 奇怪的字符输入?

转载 作者:行者123 更新时间:2023-11-30 04:14:55 24 4
gpt4 key购买 nike

我在下面的程序中使用 str.erase() 函数来删除输出的特定部分。但最后我得到了像这样的奇怪输出����

我的文件内容是Current name of the file = 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;
}

我的程序的输出是

Current name of the file = ABCD-1234
ABCD-1234

����

RUN FINISHED; exit value 0; real time: 10ms; user: 0ms; system: 0ms

最佳答案

在读取输入之前,您正在检查 eof()。修改循环如下:

while ( 1 )
{
getline (myfile,line);
if ( myfile.eof() )
break;

// Rest of the loop
}

关于c++ - 文件 I/O 操作 - 奇怪的字符输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18613397/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com