我正在编写一个代码,要求我忽略注释行(即以#符号开头的行)直到行尾。我正在使用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;
}
答案 0 :(得分: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;
}
答案 1 :(得分: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;
}