C++逐行读取txt

C++读取txt文件的时候可以使用std::ifstream来实现,如果打开文件失败的话,其变量会是空的,所以可以用来判断是否打开成功。

 #include <stdlib.h>
 #include <fstream>
 #include <string>
 #include <iostream>
 
int main(int argc, char* argv[])
{
    std::ifstream fIn("str.txt");
    if (fIn)
    {
        std::string str;
        while (std::getline(fIn, str))
        {
            std::cout << str << std::endl;
        }
    }
    else
    {
            std::cout << "Open file faild." << std::endl;
    }
    
    fIn.close();
    system("pause");
    return 0;
}

运行的结果如下:

懒拂鸳鸯枕,

休缝翡翠裙,

罗帐罢炉熏。

近来心更切,

为思君。

上善若水,为而不争。
原文地址:https://www.cnblogs.com/Bearoom/p/11721764.html