gpt4 book ai didi

c++ - 从 Qt4 中的文本文件中逐字读取

转载 作者:行者123 更新时间:2023-11-28 03:40:43 25 4
gpt4 key购买 nike

我想在 Qt4 中逐字读取一个文本文件(老实说,我对 Qt4 还是个新手),我想在另一个文件中每行写入一个字。我可以在 C++ 中毫无问题地执行此操作,但是当我尝试在 Qt4 中使用 ifstream 和 ofstream 时,我遇到了错误。这是我的 Qt4 代码(在按钮的事件监听器中)

// a string that holds the text inside the File Name index
QString str = ui->txtIndex->toPlainText();

// Check if this is a text file
if(str.endsWith(".txt")){
qDebug() << "a file";

// Create a File object that points to the file we input in the File Name
QFile mFile("/home/mohamed/Desktop/index.dat");
QFile readFile(str);

// Check if there is a problem
if(!mFile.open(QFile::WriteOnly | QFile::Append )){
qDebug() << "Could not open the file for writing";
return;
}




QTextStream in(&readFile);
if(!readFile.open(QFile::ReadOnly | QFile::Text )){
qDebug() << "Could not open the file for writing";
return;
}
// a text stream object that will print in the the file
QTextStream out(&mFile);

QString mText = in.readAll();
mText.replace("de","BURGER");
ui->txtSearchResult->setText(mText);
out << mText;

///home/mohamed/NetBeansProjects/indexing/fichier.txt


mFile.flush();

readFile.close();
mFile.close();


}

else{
qDebug() << " A FOLDER";
}

这是我的正常 C++ 代码,运行良好!

#include <cstdlib>
#include <iostream>
#include <fstream>
#include<cstdlib>
#include <dirent.h>
using namespace std;

bool searchArray(string s, string undesired[]){
for(int i=0; i<50;i++){
if(undesired[i] == s){
return true;
break;
}
}
return false;
}
int main(int argc, char** argv) {
// array filled with undesired words
string undesired[50] = {"je","tu","il","nous","faut","faire","de","ce","se"};
// the directory


// the file to read from
ifstream reader("fichier");
// the file to write to
ofstream writer("index.dat", ios_base::app);
string word, message =" ";
int count = 0;


while(!reader.eof()){ // while there still is stuff to read
reader >> word; // read one word

if(!searchArray(word,undesired)){ // if it's an undesired word

writer << word <<"\t\t\t\t" <<count<<endl;// print it in the text

cout<<"word inserted"<<endl;
}
count++;
}






return 0;

最佳答案

你可以结合QString::splitQStringList::join实现您的目标:

#include <QFile>
#include <QStringList>
#include <QCoreApplication>
#include <QTextStream>

int main()
{
QFile ifile("in.txt");
ifile.open(QIODevice::ReadOnly | QIODevice::Text);

// read whole content
QString content = ifile.readAll();
// extract words
QStringList list = content.split(" ");

ifile.close();

QFile ofile("out.txt");
ofile.open(QIODevice::WriteOnly | QIODevice::Text);

QTextStream out(&ofile);

// join QStringList by "\n" to write each single word in an own line
out << list.join("\n");

ofile.close();

return 0;
}

关于c++ - 从 Qt4 中的文本文件中逐字读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9352708/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com