2013-04-08 81 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

相关问题