【问题标题】:Removing comments from C++ string从 C++ 字符串中删除注释
【发布时间】:2014-04-22 08:53:17
【问题描述】:

我正在尝试做一个从以前编写的程序中删除 cmets 的项目。从理论上我认为它应该可以工作,但由于某种原因,输出文件最后总是为空......请以任何方式提供帮助......(PS抱歉,如果缩进马虎,复制和粘贴对我来说似乎从来没有好过)

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

using namespace std; 


void comment_destroyer(ifstream&,ofstream&); 


int main (void) {


string filestart;  
string fileend;    
ifstream start;    
ofstream end;      


do {
    cout<<"Name of the file you want to remove comments from: ";
    cin >> filestart;
}  
while ( start.fail() );
cout << "What is the name of the file you want to call the stripped code?: ";
cin >> fileend; 

start.open ( filestart.c_str() );
end.open ( fileend.c_str() );

comment_destroyer (start, end);

start.close();
end.close();

return 0;
  }

// 
//Start of functions
//

void comment_destroyer(ifstream& start, ofstream& end){
    string line; 
    bool found = false;
    int i=0;

    while (! start.eof()){
        getline(start,line); 

        if (line.find("/*")<line.length())
        found = true;
        if (!found){
            for (int i=0;i<line.length();i++)
                {
                    if(i<line.length())
                    if ((line.at(i)=='/') && (line.at(i+1)=='/'))
                    break;
                    else
                    end<<line[i];
                }

        end<<endl;

        }
    if (found)
        {
            if (line.find("*/")< line.length())
            found == false;
        }
    }
}

【问题讨论】:

  • 因为 cmets 真的很烦人,只是把代码弄得模糊不清?
  • 首先,不要做while (!someFile.eof()),它不会像你期望的那样工作。相反,例如while (std::getline(...))。原因是eofbit 标志直到您尝试从文件末尾之外读取时才设置。这意味着第一个循环将迭代一次到多次。
  • 您可能还想考虑一下缩进,您显示的代码中的缩进很难理解。请记住,您可以随时编辑您的问题以在之后解决这些问题。提示:问题很可能是因为 SO 上的编辑器不能很好地处理选项卡。
  • 是什么意思; line.find(/*)
  • main 函数的第一个do ... while 循环中还有一个非常大的逻辑错误。请记住,该文件尚未打开。

标签: c++ string stream


【解决方案1】:

以下部分是错误的。不是将 false 分配给 found 您使用相等运算符。

if (found)
    {
        if (line.find("*/")< line.length())
        found == false;
    }
}

== 更改为=

if (found)
    {
        if (line.find("*/")< line.length())
        found = false;
    }
}

【讨论】:

  • 该死的,它总是导致最多问题的最小的事情。谢谢!
【解决方案2】:

我认为你的条件是错误的。 如果未找到搜索词,string.find 返回 std::string::npos。根据npos,这是-1,所以表达式

 if (line.find("/*")<line.length())
    found = true;

总是将 found 设置为 true。

【讨论】:

    猜你喜欢
    • 2017-01-19
    • 1970-01-01
    • 2021-01-04
    • 1970-01-01
    • 2012-01-27
    • 1970-01-01
    • 2013-04-12
    • 1970-01-01
    • 2013-08-05
    相关资源
    最近更新 更多