-1

我正在编写一个代码,它要求我忽略注释行(即,以# 符号开头的行)直到行尾。我正在使用 linux 用 c++ 编写代码。例如:如果添加两个数字。

xxx@ubuntu:~ $ ./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;
}
4

2 回答 2

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;
}
于 2013-04-08T22:18:51.973 回答
0

Will any number of numbers based on the value you give reqd. Will also work if the first character in a line itself is # - will ask again for that line. Will also read another line if there is no number before the `#.

#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;
}
于 2013-04-08T23:03:47.110 回答