2013-04-08 32 views
-1

我在寫一段代碼,要求我忽略註釋行(即以#號開頭的行)直到行尾。我正在使用linux來編寫C++代碼。例如:在添加兩個數字的情況下。在命令提示符下忽略以'#'開頭的行

[email protected]:~ $ ./add 
Enter the two numbers to be added 
1 #this is the first number 
2 #this is the second number 
result: 3 

所以註釋行可以在任何地方。它只需要忽略整條線並將下一個值作爲輸入。

#include <iostream> 
using namespace std; 
int main() 
{ 
int a,b; 


cout<< "Enter the two numbers to be added:\n"; 
while(cin >>a >>b) 
{ 
if (a == '#'|| b == '#') 
continue; 
cout << "Result: "<<a+b; 
} 
return 0; 
} 
+8

你能展示你的嘗試?否則,我們必須對你的代碼做出假設。 – 2013-04-08 22:15:25

+0

即時通訊非常新的這個,我不知道如何在這裏添加代碼..但這裏是它.. – 2013-04-08 22:32:17

+0

點擊 - > [編輯] :) – 2013-04-08 22:34:58

回答

1

從你所顯示的,我認爲這可能是你想要的。

int main() 
{ 
    string comment; 
    int nr1,nr2; 
    // Read the first number. It should be the first one always. No comment before number! 
    cin >> nr1;    

    // See if we can read the second number Successfully. Which means it is an integer. 
    if(cin >> nr2) { 
    } 
    // Otherwise clear cin and read the rest of the comment line       
    else { 
     cin.clear();   
     getline(cin,comment); 
     // Now read the second number from the second line 
     cin >> nr2;   
    } 
    // Read the rest of second the line. 
    getline(cin,comment); 

    cout << "result: " << nr1 + nr2 << endl; 
    return 0; 
} 
+0

好的,但如果沒有評論,它必須讀取兩個數字。 – 2013-04-08 22:51:05

+0

@anusha你也想處理這個嗎? '1 2'在一行? – 2013-04-08 22:56:09

+0

@anusha。我瘋了一個編輯。看看它是否有效。 – 2013-04-08 23:05:35

0

請問任意數量根據你給reqd值數。 如果一行中的第一個字符本身是#,它也會起作用 - 將再次詢問該行。如果`#之前沒有數字,還會讀取另一行。

#include <iostream> 
#include <sstream> 
#include <ctype.h> 

using namespace std; 

int main() 
{ 
    const int reqd = 2; 
    string sno[reqd]; 
    int no[reqd]; 
    int got = 0; 
    size_t pos; 
    istringstream is; 

    cout<< "Enter "<<reqd<<" numbers to be added:\n"; 
    while(got < reqd) 
    { 
     getline(cin, sno[got]); 
     if((pos = sno[got].find('#')) && isdigit(sno[got][0])) 
     { 
      is.str(sno[got]); 
      is>>no[got]; 
      ++got; 
     } 
    } 

    int sum = 0; 
    for(int i = 0; i < reqd; ++i) 
     sum+=no[i]; 

    cout<<"Result : "<<sum; 
    return 0; 
} 
+0

我試過這個,我認爲它是返回錯誤的結果。雖然它跳過評論行..在第一行以及.. – 2013-04-09 05:52:14

+0

@anusha - 它不'C:\ tmp> a 輸入2個號碼被添加: 1 #this是第一個號碼 2 #this是第二個號碼 結果:3' – user93353 2013-04-09 05:59:08

+0

但是如果沒有註釋行,它會給出不同的答案。 – 2013-04-09 06:02:50

相關問題