如何从文件中获取字符并显示在控制台上?

How to get characters from a file and display on console?

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;
}

a 是一个字符,std::getline() returns 是一个 istream。这里有什么问题吗?您不能将 istream 分配给 char,因此代码甚至无法编译。

您可以将您的代码简化为这个工作示例:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;
int main()
{
    ifstream obj("test.txt", ifstream::in);

    if (obj.good())
    {
        std::string line;
        while (std::getline(obj, line))
        {
            for (auto& i : line)
            {
                if (i == 'x') return 0;
                cout << i << endl;
            }
        }
    }
    obj.close();
    return 0;
}

test.txt:

This is
a
test fixle

输出:

T
h
i
s

i
s
a
t
e
s
t

f
i

obj.getline() 无效。我在你的评论中看到你打算写 obj.get(),所以我会坚持使用它。

主要问题是您在 do-while 循环中打开和关闭文件,这意味着对于每次迭代,您将打开文件,读取一个字符,然后关闭文件。每次打开文件时,实际上都是从头开始,因此直到到达'x'个字符才开始阅读,但基本上是无限期。

我没有测试这个,但这似乎是你想要的(添加评论):

#include<iostream>
#include<fstream>
#include<string>

int main()
{
    std::ifstream obj("test.txt"); // open the file (no need to specify "in")
    if ( !obj ) { // check to see if the file could be opened
        std::cout << "Could not open file\n";
    } else {
        char a;
        while ( obj >> a ) { // while there's still something to read
            if ( a != 'x' ) { // if it's not an 'x' character, print it
                std::cout << a << std::endl;
            } else {
                break; // otherwise, break the loop
            }
        }
        obj.close(); // close the file
    }
    
    return 0;
}