最近学校给了一题:
输入一段代码,并删除其中的注释部分,并输出。
样例输入:
*
This is a test
*/
#include <iostream>
using namespace std;
int main() // C/C++
{
cout << "Hello World!" << endl; /* cout is c++'s printf */ /* hello world */
return 0;
}
// end of file
样例输出
#include <iostream>
using namespace std;
int main()
{
cout << "Hello World!" << endl;
return 0;
}
我自己在解决的时候试图用while((c=getchar())!=EOF)但结果也只能输入一行输出一行。
还请给个思路或者代码我自己研究研究。
一般是通过将文件读入来实现,因为测试程序会直接将所有代码输入,所以一行一行处理就可以
如果你是手动输入的话,你可以现将处理结果放入字符串数组,等到所有输入都结束再依次输出
#include <iostream>
#include <iterator>
using namespace std;
int main()
{
char c1, c2;
auto begin = istream_iterator<char>(cin);
auto end = istream_iterator<char>();
auto out = ostream_iterator<char>(cout, "");
noskipws(cin);
while (begin != end)
{
c1 = *begin++;
if (begin == end)
{
*out++ = c1;
break;
}
if (c1 == '/')
{
c2 = *begin++;
if (begin == end)
{
*out++ = c2;
break;
}
if (c2 == '*')
{
while (begin != end && !(*begin++ == '*' && *begin++ == '/'))
;
}
else if (c2 == '/')
{
while (begin != end && *begin++ != '\n')
;
}
else
{
*out++ = c1;
*out++ = c2;
}
}
else
{
*out++ = c1;
}
}
return 0;
}
$ g++ -Wall main.cpp
$ cat test.cpp
/*
This is a test
*/
#include <iostream>
using namespace std;
int main() // C/C++
{
cout << "Hello World!" << endl; /* cout is c++'s printf */ /* hello world */
return 0;
}
// end of file
$ ./a.out < test.cpp
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!" << endl;
return 0;
}
#include <stdio.h>
int main()
{
int a;
while (scanf("%d", &a) == 1)
{
printf("%d", a);
}
return 0;
}