如何从文件中获取字符并在控制台上显示?
我从有关文件处理的注释中获得了此代码。据我了解此代码的了解,我想使用此代码在文件中达到x的字符。为什么我只得到第一个角色?如果此代码不正确,我应该如何更改代码以获取字符直到达到X?请帮助我理解这一点。<
#include<iostream>
#include<fstream>
#include<string.h>
#include<string>
using namespace std;
int main()
{
char a = '-';
do
{
ifstream obj("test.txt", ifstream::in);// in would mean import from txt to ram
// cout << obj << endl;
if (obj.good() && a != obj.peek())
{
a = obj.getline();
cout << a << endl;
}
obj.close();
} while (a != 'x');
return 0;
}
I got this code from notes about file handling. From what I understand about this code, I want to get characters till x is reached in the file using this code. Why am I getting only the first character? If this code is incorrect, how should I alter the code to get characters till x is reached? Please help me understand this.<
#include<iostream>
#include<fstream>
#include<string.h>
#include<string>
using namespace std;
int main()
{
char a = '-';
do
{
ifstream obj("test.txt", ifstream::in);// in would mean import from txt to ram
// cout << obj << endl;
if (obj.good() && a != obj.peek())
{
a = obj.getline();
cout << a << endl;
}
obj.close();
} while (a != 'x');
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
obj.getline()
无效。我在您的评论中看到您打算编写obj.get()
,因此我会坚持使用它。主要问题是您正在打开和关闭
do-while
循环中的文件,这意味着,对于每次迭代,您将打开文件,读取字符,然后关闭文件。每次打开文件时,您实际上是从开始开始的,因此,直到您到达'x'
字符之前,您都不会读取,但基本上是无限的。我没有测试过,但这似乎是您想要的(评论):
obj.getline()
isn't valid. I see in your comments you meant to writeobj.get()
, so I'll stick with using that.The main problem is that you are opening and closing the file within your
do-while
loop, which means that, for each iteration, you will open the file, read a character, then close the file. Each time you open the file, you actually start at the beginning, and thus you will not read until you get to an'x'
character, but basically infinitely.I didn't test this, but this seems to be what you want (comments added):
a
是一个字符,std :: getline()
返回istream
。这里没有什么问题吗?您不能将iStream
分配给char
,因此代码甚至没有编译。您可以将代码简化到此工作示例中:
test.txt:
输出:
a
is a character andstd::getline()
returns anistream
. Isn't there something wrong here? You cannot assign anistream
to achar
, so the code doesn't even compile.You can simplify your code into this working example:
test.txt:
Output: