C ++:从字符串中删除注释?

时间:2016-09-11 22:06:23

标签: c++ string comments erase

我正在做一个从文本文件中读取数据的作业,我必须将数据放入向量中,同时过滤掉以0和注释开头的数字。除了过滤评论之外,我把一切都搞定了。理论上我应该有所作为,但我只是在执行它时遇到了麻烦。这是问题代码:

vector<string> nums_after;
for(int i = 0; i < nums_before.size(); i++)
{
    string current = nums_before[i];
    if (current.front() == '(')
    {
        current.erase(current.find("(*"), current.find("*)"));
    }
    if (current.front() == '0')
    {
        continue;
    }
    nums_after.push_back(current);
}

我的示例文件如下所示:

101481
10974
1013
(* comment *)0
28292
35040
35372
0000
7155
7284
96110
26175

但是我的代码只过滤了(*甚至没有星号后面的空格。我想我在组合erase()和find()函数时遇到了麻烦。有人有什么建议吗?

编辑:意识到我的问题是注释行被分解为三个单独的行:(*,comment和*)0。我现在怀疑我的getline功能有问题。这就是它的样子:

int main() {
string line;
string fileName;
cout << "Enter the name of the file to be read: ";
cin >> fileName;

ifstream inFile{fileName};

istream_iterator<string> infile_begin {inFile};
istream_iterator<string> eof{};
vector<string> nums_before {infile_begin, eof};
while (getline(inFile, line))
{
    nums_before.push_back(line);
}

这是在第一段代码之前。

3 个答案:

答案 0 :(得分:0)

nums_before中有什么?我猜是用空格分割的全文? 在这种情况下,有意义的是它只删除(*,因为那是你正在查看的当前字符串中的内容是&#34;(*&#34;。下一个字符串是&#34;注释&# 34;下一个是&#34; *)0&#34;。

答案 1 :(得分:0)

在这种情况下,您应该选择stack数据结构或反向迭代。

void func ( int &error, int inc, int &i ) {
    error += inc;
    i -= 2;
}

string output;
for ( int i=nums_before.size()-1; i>=0; ++i ) {
    if ( nums_before[i] == ')' && nums_before[i-1] == '*' ) {
        static int error;
        func ( error, 1, i );

        while ( error != 0 ) {
            if ( nums_before[i] == ')' && nums_before[i-1] == '*' ) 
                func ( error, 1, i );
            else if ( nums_before[i] == '*' && nums_before[i-1] == '(' ) 
                func ( error, -1, i );
            else --i;
        }
    } else output += nums_before[i];
}

cout << output.reverse() << endl;

输入:101481 10974 1013 (* comment *)0 28292 35040 35372 0000 7155 7284 96110 26175

输出:101481 10974 1013 0 28292 35040 35372 0000 7155 7284 96110 26175

答案 2 :(得分:0)

简单的解决方案,但不支持嵌套注释:

std::string removeComments(std::string str)
{
    std::string::size_type begin, end;
    while((begin = str.find("(*")) != std::string::npos)
    {
        if(((end = str.find("*)")) != std::string::npos) && (end > begin))
            str.erase(begin, end - begin + 2);
        else
            break;
    }
    return str;
}

测试:

std::string test = "1745 2355 (* comment *) 0 1454 4352 4234 (* comment *)";
std::cout << removeComments(test) << std::endl;

输出:

1745 2355  0 1454 4352 4234

不使用功能的示例:

std::vector<std::string> strings;
for(int i=0; i<strings.size(); ++i)
{
    std::string::size_type begin, end;
    while((begin = strings[i].find("(*")) != std::string::npos)
    {
        if(((end = strings[i].find("*)")) != std::string::npos) && (end > begin))
            strings[i].erase(begin, end - begin + 2);
        else
            break;
    }
}
相关问题