программа по обработке строк
Вобщем есть код программы из приложения QT widgets, которая обрабатывает строки. А я хочу ее запустить в консольном приложении, но что-то пока не особо получается.
#include <QCoreApplication>
#include <iostream>
#include <fstream>
using namespace std;
const QString separators = "\n !@:?#$%^&*()_+{}\\|/,.!-";
bool isSeparator(QChar ch)
{
return separators.contains(ch);
}
const QString digits = "0123456789";
bool isNumeric(QChar ch)
{
return digits.contains(ch);
}
string reverse_content(const char* charstr)
{
string result="";
for (int i=strlen(charstr)-1;i>=0;i--)
result+=charstr[i];
return result;
}
QString processLine(QString line, bool rev)
{
QString word("");
QString new_line("");
QString result("");
QChar prev_c('\n');
int len = line.length();
for (int i=0;i<=len;i++)
{
QChar c= i<len? line.at(i):'\n';
if (isSeparator(c))
{
if (c==' ' && ((word.length()==0 && new_line.length()==0) || prev_c==' '))
{
// пробелы в начале или несколько пробелов между словами - ничего не делаем
} else
if (c=='-' && i+1!=len && isNumeric(line.at(i+1)))
{
// это число со знаком минус
word+=c;
} else
{
if (word.length()>0)
{
if (rev)
{
std::reverse(word.begin(), word.end());
//word = reverse_content(word.c_str());
}
new_line+=word;
}
if (c=='.' && prev_c == ' ')
{
// нужно удалить пробел перед точкой
new_line = new_line.left(new_line.length()-1);
}
if (c!='\n') new_line+=c;
if (c=='.' || c=='\n')
{
if (new_line.length()>0 && new_line!=".") result += (new_line+'\n');
new_line="";
word="";
}
word = "";
}
} else word+=c;
prev_c = c;
}
if (new_line.length()>0) result += new_line;
return result;
}
int main(){
string input = "input.txt";
string output1 = "output.txt";
string output2 = "output2.txt";
int res=processLine(input,output1,false);
if (res){
cout << input <<" to "<< output1 <<" - OK\n";
}
else{
cout<< input << " to "<< output1 <<" - ERROR\n";
return 0;
}
res=processLine(output1,output2,true);
cout << output1 <<" to "<< output2 <<" - "<< (res?"OK\n":"ERROR\n");
return 0;
}
Через это поппробовала ifstream ifile("input.txt"); ofstream ofile("output.txt"); Хотя подозрения, что дело совсем не в этом, не особо понимаю что делать
Ответы (1 шт):
Вроде я разобрался в этом и сделал, но тому, кто писал код (в вопросе) - очень советую почитать про форматирование кода.
Также не совсем понятно чего вы пытались добиться этим:
int res=processLine(input,output1,false);
Вы вызываете функцию, принимающую два аргумента, а передаёте ей три, а потом ещё и пытаетесь возвращаемое значения типа string присвоить переменой типа int (int тип данных для целых чисел). Почитайте про типы данных и поймёте, что далеко не всё можно положить в int.
Сделал я без фишек QT вроде QString или QChar. В main вызывается функция обработки текста, результат записывается в файл output.txt. Вы пытались прочитать файл, вызывая функцию обработки, и имея только название файла (но не сам файл), а потом результат положить в переменную int и ждали, что в файле output.txt, которого опять же нет (только имя) окажется текст. Эта функция не читает и не записывает ничего в файл. И тем, что вы дадите ей имена нужных вам файлов - вы ничего не добьётесь. Она просто обработает имена и вернёт их. И вообще, лучше, как сказал Andrej Levkovitch сначала учите язык, а потом уже пишите код.
Также в файл ouput2.txt записывается тот же обработанный текст, но наоборот.
#include <iostream>
#include <cctype>
#include <fstream>
using namespace std;
const string separators = "\n !@:?#$%^&*()_+{}\\|/,.!-";
bool isSeparator(char ch)
{
return separators.find(ch) != string::npos;
}
const string digits = "0123456789";
bool isNumeric(char ch)
{
return digits.find(ch) != string::npos;
}
string reverse(const char* charstr)
{
string result="";
for (int i = sizeof(charstr) - 1; i >= 0; --i)
result += charstr[i];
return result;
}
string processLine(string line, bool rev)
{
string word(""), new_line(""), result("");
char prev_c('\n'), c;
unsigned long long len = line.length();
for (unsigned long long i = 0; i <= len; ++i) {
c = i < len ? line.at(i) : '\n';
if (isSeparator(c)) {
if (isspace(c) && ((word.length() == 0 && new_line.length() == 0) || isspace(prev_c))) {
// пробелы в начале или несколько пробелов между словами - ничего не делаем
}
else {
if (c == '-' && i + 1 != len && isNumeric(line.at(i+1))) {
// это число со знаком минус
word += c;
}
else {
if (word.length() > 0) {
if (rev) {
//std::reverse(word.begin(), word.end());
word = reverse(word.c_str());
}
new_line += word;
}
if (c == '.' && isspace(prev_c)) {
// нужно удалить пробел перед точкой
new_line.erase(i - 1, 1);
}
if (c != '\n') new_line += c;
if (c == '.' || c == '\n') {
if (new_line.length()>0 && new_line!=".") result += (new_line+'\n');
new_line="";
word="";
}
word = "";
}
}
}
else word += c;
prev_c = c;
}
if (new_line.length() > 0) result += new_line;
return result;
}
int main()
{
string input = "input.txt";
string output = "output.txt";
string output_2 = "output2.txt";
ifstream file(input);
if (!file.is_open()){
cout << "Error while opening the input file.";
return 1;
}
ofstream out_file(output);
if (!out_file.is_open()){
cout << "Error while opening the output file.";
file.close();
return 1;
}
ofstream out_file2(output_2);
if (!out_file2.is_open()){
cout << "Error while opening the output 2 file.";
file.close();
out_file.close();
return 1;
}
string tmp = "", res;
while(getline(file, tmp)){
res = processLine(tmp, false);
out_file << res;
res = processLine(tmp, true);
out_file2 << res;
}
out_file.close();
out_file2.close();
file.close();
cout << "Programm finished successfully";
return 0;
}