当我找到行尾时如何停止阅读

时间:2017-04-30 12:19:42

标签: c++

我试图从文件中读取并在我点击结束时停止。事情是,它似乎没有工作。¯_(ツ)_ /¯任何想法为什么?

#include <iostream>
#include <fstream>
using namespace std;

int main(){
    char a;
    ifstream myfile;
    myfile.open("text.txt");
    while (!myfile.eof())
    {
    myfile>> a;
    if (a=='\n')
    cout << "end of line";

    }
myfile.close();
}
我读过

文本文件:

text file i read

4 个答案:

答案 0 :(得分:1)

请尝试while (myfile.get(a))

while (myfile.get(a))
{
    if (a=='\n')
        cout << "end of line";

}

答案 1 :(得分:1)

为什么要让事情变得比实际更难。如果要解析行,请使用std::getline()

#include <iostream>
#include <fstream>

int main(int argc, char *argv[]) {
    std::ifstream myfile("text.txt");

    std::string line;
    while (std::getline(myfile, line)) {
        std::cout << "end of line" << std::endl;
    }
}

答案 2 :(得分:0)

使用for循环

std::ifstream ifs( "file" );
for( char chr = 0; ifs.peek() != '\n'; ifs.get( chr ) ){
    std::cout << chr;
}
ifs.close();

答案 3 :(得分:0)

我只是重写你的代码:

#include <iostream>
#include <fstream>
using namespace std;

int main(){
    char a;
    ifstream myfile;
    myfile.open("/Users/sijan/CLionProjects/test2/text.txt",ifstream::in);
    while (myfile.get(a))
    {
        cout<< a;

        if (a=='\n')
            cout << "end of line\n";
    }

    if (myfile.eof())
        cout << "end of file";
    myfile.close();
}
相关问题