чтение нескольких строк из файла .txt как строки, удаление пробелов и создание нового файла для вывода - PullRequest
0 голосов
/ 12 июня 2018

Я пытаюсь написать программу, которая читает информацию из файла .txt, удаляет ненужные пробелы между словами / частями и сохраняет результат в новый выходной файл .txt.

Мне удалосьполучить большую часть этой работы после просмотра большого количества вопросов на сайте для некоторых указаний.В настоящее время у меня есть чтение кода из файла .txt и запись в новый, мне также удалось получить его, чтобы удалить ненужные пробелы.Однако теперь, когда мне удалось запустить эту часть, она только прочитает одну строку из исходного файла .txt и остановится на этом.Теперь он также записывает в выходной файл каждую версию строки, которую он захватывает, удаляя каждый пробел.

Вот код, который мне удалось написать до сих пор, любые советы по любой части были бы благодарны, так как я до сих порlearning.

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

// Declarations
string Inputfile, Outputfile;
ifstream OriginalInputFile("Sample of input file.txt");
ofstream NewOutputFile("Output File.txt");
ifstream OutputFileRead("Output File.txt");

int main()
{
    if (!OriginalInputFile.is_open()) { 
        cout << "Input file could not be opened! Terminating!" << endl;
        return 1;
    }
    if (OriginalInputFile.is_open())
    {
        NewOutputFile << "                         EXCEPTIONS REPORT                    " << endl;
        NewOutputFile << "                       PP TO FS OO INTERFACE                  " << endl;
        NewOutputFile << "     =========================================================" << endl;

        while ( getline (OriginalInputFile,Inputfile) )
            while(true)
            {
                unsigned int pos = Inputfile.find("  ");
                if(pos == string::npos)
                {
                    break;
                }
                else 
                {
                    Inputfile.erase(pos, 1);
                }
                {
                    Outputfile = Inputfile;
                    NewOutputFile << Outputfile << endl;
                    OriginalInputFile.close();
                }
            }
    }

    if (!NewOutputFile.is_open()) { 
        cout << "Output file could not be opened! Terminating!" << endl;
        return 1;
    }
    if (NewOutputFile.is_open()) 
    {
        while ( getline (OutputFileRead, Outputfile))
        {
            cout << Outputfile << endl;
        }
        {
            NewOutputFile.close();
        }
    }
    return 0;
}

Вот пример входных данных:

BABROUB00008         PERSON1             MARTIN                        M               0610196129081978D B09          PM           Brough         B010           B00008    sfsf.testmailbox@mysite.com                                       54289                                                      
BABROUB00012         PERSON2             TIMOTHY                       T               1708196407091981D B08          PP           Brough         B306           B00012    sfsf.testmailbox@mysite.com   

                                53899 

Вот небольшой пример выходных данных, чтобы показать, что сейчас происходит:

BABROUB00008 PERSON1 MARTIN M 0610196129081978D B09 PM Brough B010 B00008 sfsf.testmailbox@mysite.com          54289                                                      
BABROUB00008 PERSON1 MARTIN M 0610196129081978D B09 PM Brough B010 B00008 sfsf.testmailbox@mysite.com         54289                                                      
BABROUB00008 PERSON1 MARTIN M 0610196129081978D B09 PM Brough B010 B00008 sfsf.testmailbox@mysite.com        54289                                                      
BABROUB00008 PERSON1 MARTIN M 0610196129081978D B09 PM Brough B010 B00008 sfsf.testmailbox@mysite.com       54289                                                      
BABROUB00008 PERSON1 MARTIN M 0610196129081978D B09 PM Brough B010 B00008 sfsf.testmailbox@mysite.com      54289                                                      
BABROUB00008 PERSON1 MARTIN M 0610196129081978D B09 PM Brough B010 B00008 sfsf.testmailbox@mysite.com     54289                                                      
BABROUB00008 PERSON1 MARTIN M 0610196129081978D B09 PM Brough B010 B00008 sfsf.testmailbox@mysite.com    54289                                                      
BABROUB00008 PERSON1 MARTIN M 0610196129081978D B09 PM Brough B010 B00008 sfsf.testmailbox@mysite.com   54289                                                      
BABROUB00008 PERSON1 MARTIN M 0610196129081978D B09 PM Brough B010 B00008 sfsf.testmailbox@mysite.com  54289                                                      
BABROUB00008 PERSON1 MARTIN M 0610196129081978D B09 PM Brough B010 B00008 sfsf.testmailbox@mysite.com 54289               

Где возможно, я хочу, чтобы строка без пробелов помещалась в вывод сама по себе, не видя всей работы.Затем то же самое для следующей строки из исходного ввода, которая в настоящее время не обрабатывается.И это должно было бы выполняться для любого количества строк исходного файла .txt, которые могут меняться каждый раз.

1 Ответ

0 голосов
/ 12 июля 2018

Вы звоните OriginalInputFile.close() после записи каждой строки в выходной файл.Таким образом, перед закрытием файла читается только первая строка входного файла (после чего getline(OriginalInputFile,Inputfile) не будет задерживаться, поэтому верхний цикл while завершается после одной итерации.

Вот непроверенное редактирование, которое, мы надеемся, сработает:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

// Declarations
string Inputfile, Outputfile;
ifstream OriginalInputFile("Sample of input file.txt");
ofstream NewOutputFile("Output File.txt");
ifstream OutputFileRead("Output File.txt");

int main()
{
    if (!OriginalInputFile.is_open()) { 
        cout << "Input file could not be opened! Terminating!" << endl;
        return 1;
    }
    if (!NewOutputFile.is_open()) { 
        cout << "Output file could not be opened! Terminating!" << endl;
        return 1;
    }

    NewOutputFile << "                         EXCEPTIONS REPORT                    " << endl;
    NewOutputFile << "                       PP TO FS OO INTERFACE                  " << endl;
    NewOutputFile << "     =========================================================" << endl;

    while ( getline (OriginalInputFile,Inputfile) )
    {
        for(unsigned int pos=Inputfile.find("  "); pos!=string::npos; pos=Inputfile.find("  "))
        {
            Inputfile.erase(pos, 1);
        }
        Outputfile = Inputfile;
        NewOutputFile << Outputfile << endl;
    }
    OriginalInputFile.close();

    while ( getline (OutputFileRead, Outputfile))
    {
        cout << Outputfile << endl;
    }
    NewOutputFile.close();
    return 0;
}
...