c++有没有类似qt这种逐行读取txt文件的方式

while (!file.atEnd())
{
line = file.readLine();
ui->label->setText(line);
line = line + "\n";
arr = arr + line;
ui->label->setText(arr);
}
没有没类似这种的额

c++

2个回答

scanf("%49[^\n]",readbuf);就是读一行的

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    string filePath = "iotest.txt";

    char readbuf[50] = {};
    string readstr = "";

#if 1 //c++风格
    ifstream file(filePath.c_str(),ios::in);
    if(!file)
    {
        std::cout << "open file <" << filePath << "> failed!!";
        exit(1);
    }


#if 1
    while(file.getline(readbuf,sizeof(readbuf)))
    {
        std::cout << readbuf << endl;
    }
#else
    while(getline(file,readstr))
    {
        std::cout << readstr << endl;
    }
#endif
    file.close();

#else //c 风格
    FILE *fp = fopen(filePath.c_str(),"r");
    if(!fp)
    {
        printf("open file <%s> failed!\n",filePath.c_str());
        exit(1);
    }
    while(!feof(fp)) {
        if(fgets(readbuf,sizeof(readbuf),fp)!=NULL)
        printf("%s",readbuf);
    }
    printf("\n");
    fclose(fp);
#endif

    return 0;
}
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问