C ++ Проблема с обнаружением пространства в строке массива - PullRequest
0 голосов
/ 16 сентября 2018

В настоящее время я пишу программу, в которой я пытаюсь отфильтровать лишние пробелы, поэтому, если в строке более 1 пробела, я отбрасываю остальные, оставляя только один

Но это только первый шаг, потому чтоцель программы - проанализировать текстовый файл с инструкциями по сборке mips.

До сих пор я открыл файл, сохранил содержимое в векторе, а затем сохранил векторный контент в массиве.Затем я проверяю, если вы найдете символ 2 раза подряд, сдвиньте массив влево.

Проблема в том, что код работает хорошо для любой другой буквы, кроме символа пробела.(В приведенном ниже коде я проверяю его с помощью символа 'D', и он работает)

#include <iostream>
#include <cmath>
#include <fstream>
#include <cstdlib>
#include <vector>
#include <algorithm>

using namespace std;

class myFile {
    vector<string> myVector;
public:
    void FileOpening();
    void file_filter();
};

void myFile::FileOpening() {
    string getcontent;
    ifstream openfile;     //creating an object so we can open files

    char filename[50];
    int i = 0;

    cout << "Enter the name of the file you wish to open: ";
    cin.getline(filename, 50);   //whatever name file the user enters, it's going to be stored in filename
    openfile.open(filename);     //opening the file with the object I created

    if (!openfile.is_open())       //if the file is not opened, exit the program
    {
        cout << "File is not opened! Exiting the program.";
        exit(EXIT_FAILURE);
    };

    while (!openfile.eof())             //as long as it's not the end of the file do..
    {
        getline(openfile, getcontent);     //get the whole text line and store it in the getcontent variable

        myVector.push_back(getcontent);
        i++;
    }
}

void myFile::file_filter() {
    unsigned int i = 0, j = 0, flag = 0, NewLineSize, k, r;
    string Arr[myVector.size()];

    for (i = 0; i < myVector.size(); i++) {
        Arr[i] = myVector[i];

    }

    //removing extra spaces,extra line change
    for (i = 0; i < myVector.size(); i++) {
        cout << "LINE SIZE" << myVector[i].size() << endl;
        for (j = 0; j < myVector[i].size(); j++) {

            //If I try with this character for example,
            //it works (Meaning that it successfully discards extra 'Ds' leaving only one.
            // But if I replace it with ' ', it won't work. It gets out of the loop as soon
            //as it detects 2 consecutive spaces.

            if ((Arr[i][j] == 'D') && (Arr[i][j + 1] == 'D')) {
                for (k = j; k < myVector[i].size(); k++) {
                    Arr[i][k] = Arr[i][k + 1];
                    flag = 0;
                    j--;
                }
            }
        }
    }


    for (i = 0; i < myVector.size(); i++) {
        for (j = 0; j < myVector[i].size(); j++) //edw diapernw tin kathe entoli
        {

            cout << Arr[i][j];
        }
    }
}

int main() {
    myFile myfile;

    myfile.FileOpening();
    myfile.file_filter();
}

Мой вопрос: почему он работает со всеми символами, кроме пробела, и как это исправить??Спасибо заранее!

1 Ответ

0 голосов
/ 28 июня 2019

Ничего себе. Много строк кода. Я могу только рекомендовать больше узнать о STL и алгоритмах.

Вы можете прочитать весь файл в вектор с помощью вектора-конструктора range и std::istream_iterator. Затем вы можете заменить один или несколько пробелов в строке, используя std::regex. Это действительно не сложно.

В приведенном ниже примере я делаю всю работу с двумя строками кода в функции main. Пожалуйста, посмотрите:

#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <string>
#include <fstream>
#include <regex>

using LineBasedTextFile = std::vector<std::string>;

class CompleteLine {    // Proxy for the input Iterator
public:
    // Overload extractor. Read a complete line
    friend std::istream& operator>>(std::istream& is, CompleteLine& cl) { std::getline(is, cl.completeLine); return is; }
    // Cast the type 'CompleteLine' to std::string
    operator std::string() const { return completeLine; }
protected:
    // Temporary to hold the read string
    std::string completeLine{};
};

int main()
{
    // Open the input file
    std::ifstream inputFile("r:\\input.txt");
    if (inputFile)
    {
        // This vector will hold all lines of the file. Read the complete file into the vector through its range constructor
        LineBasedTextFile text{ std::istream_iterator<CompleteLine>(inputFile), std::istream_iterator<CompleteLine>() };
        // Replace all "more-than-one" spaces by one space
        std::for_each(text.begin(), text.end(), [](std::string& s) { s = std::regex_replace(s, std::regex("[\\ ]+"), " "); });

        // For Debug purposes. Print Result to std::out
        std::copy(text.begin(), text.end(), std::ostream_iterator<std::string>(std::cout, "\n"));
    }
    return 0;
}

Надеюсь, я мог бы дать вам некоторое представление о том, как действовать.

...