2016-09-11 1 views
1

現在、ファイルを読み込んでから、その行数を読み戻すプログラムを作成中です。私はちょうどプログラムのカウントをラインにするかどうかについて何か助けが必要です。現在、私は持っている:コメントや空白行だけをスキップして、C++でファイル内のコード行をカウントする

code... //comment 
code... /* comment 
/* comment */ code... 

任意のヒントをか:

getline(file, line); 
if(line.empty() || line.find("//") || line.find("**") || line.find("/*") || line.find("*/")) 
{ skip line } 

唯一の問題は、それはまだ、コードを持っていますが、コメントを持っている場合、プログラムが行をカウントされませんです(次の例のいずれか)助けて?

+0

何 'のstd :: coutの<< "//" <<はstd ::についてendl; 'と' int ** ptr' – xinaiz

+0

あなたはちょうどそのような行を数えることはできません(うまくできますが間違っているでしょう)。複数行の '/ * * /'コメントはどうでしょうか?レクサー/トークナイザーが必要で、あなたがいる状態を暗記します(コメントかどうか)。 –

+0

初心者向けの優れたプログラミングです。テキストを通ってあなたの歩みの状況を追跡するためのシンプルな状態マシンを構築してください。 –

答えて

0

あなたは次のように可能性が必要なものを達成するためのアルゴリズム:
を(注:このコードは未テストです)

std::vector<std::string> lines; 
//collect all the lines in the vector 

//iterate through the vector, removing all leading and trailing whitespace characters 
for(auto& line : lines) 
{ 
    std::string::size_type pos = line.find_last_not_of("\n\t "); 
    if(pos != std::string::npos) 
    line.erase(pos + 1) 

    pos = line.find_first_not_of("\n\t "); 
    if(pos != std::string::npos && pos != 0) 
    line.erase(0, pos); 
} 

//remove all comment-only lines and blank lines 
bool comment_block = false; 
lines.erase(std::remove_if(lines.begin(), lines.end(), [&comment_block](const std::string& line){ 
    //if it's empty, remove it 
    if(line.empty()) 
    return true; 

    //if it starts with "//" it can't have code after it 
    if(line.find("//") == 0) 
    return true; 

    //if it starts with "/*", it begins a comment block 
    //(or if we're already in a comment block from earlier...) 
    if(comment_block || line.find("/*") == 0) 
    { 
    auto pos = line.find("*/"); 
    if(pos == std::string::npos) 
    { 
     //if we can't find "*/" in this line, this is a comment block 
     //so this line is all comments and it continues to the next line 
     comment_block = true; 
     return true; 
    } 
    //if we did find "*/" in this line, we are no longer in a comment block 
    //(if we were already) 
    comment_block = false; 
    //Also, if "*/" is the last thing in this line, it's all comments 
    return pos == line.length() - 2; 
    } 

    return false; 
}), lines.end()); 
+0

いいえ、申し訳ありませんが、それは簡単ではありません。あなたのアルゴリズムは、 'cout <<" // ";"をコメント行としてタグ付けします。他の答えほど悪くないですが、依頼されたことはまだありません。神の愛のために、あなた自身のロールをしようとしないでください。この目的のために設計されたツールを使用してください。これはあなたのように見せるより**複雑な方法です**。 – IInspectable

+0

@IInspectableさて、私のアルゴリズムでは、 'cout <<" // "をコメント行としてタグ付けしません。' // 'は空白を削除した後に行頭になければなりません。 '/ *'と同じです – Altainia

+0

実際にはそうかもしれません。まだブロックコメントの終わりを確実にテストすることはできません。 'cout <<" */";'はブロックコメントを間違って終了させます。また、ブロックコメントの開始部分を確実に見つけ出すことはできません。これは確かに望ましくない。 – IInspectable

関連する問題