【问题标题】:C++ Problem with space detection in an Array StringC++ 数组字符串中的空间检测问题
【发布时间】:2023-04-02 16:56:01
【问题描述】:

我目前正在编写一个程序,尝试过滤多余的空格,所以如果连续有 1 个以上的空格,我会丢弃其余的,只留下一个

但这只是第一步,因为程序的目的是解析一个带有 mips 汇编指令的 txt 文件。

到目前为止,我已经打开了文件,将内容存储在向量中,然后将向量内容存储在数组中。然后我检查一下,如果您连续 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();
}

我的问题是,为什么它适用于除空格之一之外的所有字符,我该如何解决这个问题? 提前致谢。

【问题讨论】:

  • 那么...问题是什么?
  • 我的问题是,为什么它对除空格之外的所有字符都有效?
  • 您是否尝试过将代码剥离到 MCVE 或使用调试器单步执行您的代码?
  • 首先,不要使用! openfile.eof()。这是always wrong。其次,考虑将您的代码拆分为可以执行更简单任务的函数。这样,您的代码将更容易测试。第三,请改进您的代码格式。你有很多无用的空行之类的。
  • string Arr[myVector.size()]; - 使用 gnu 扩展。技术上不便携。你可以通过克隆你的载体来替代。

标签: c++ arrays space


【解决方案1】:

哇。多行代码。我只能建议更多地了解 STL 和算法。

您可以使用向量“范围”构造函数和std::istream_iterator 将完整文件读入向量。然后,您可以使用std::regex 替换字符串中的一个或多个空格。这真的不复杂。

在下面的示例中,我完成了所有工作,在函数 main 中使用了 2 行代码。请看:

#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;
}

我希望我能给你一些关于如何进行的想法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-12
    • 1970-01-01
    • 1970-01-01
    • 2014-07-16
    相关资源
    最近更新 更多