之前某次做ACM一道字符串题的时候,题目要求每次读入一整行(可能会有空格)。而调试过程中发现每次读取第一行都是一个空行。于是开始辛苦的debug过程。
后来发现,读入整行调用了gets()函数,而在这之前使用cin读取了两个整数。然而在输入过程中cin会读取到控制台\0前一位,因此gets()函数的第一次读入便终止于cin残留的\0.
debug中利用编译器的debug功能,通过观察变量的值最终确定问题发生在cin和gets()过程之中。于是查阅网上资料终于解决问题。
#include<cstdio>
#include<map>
#include<iostream>
#include<cstring>
using namespace std;
map< string, string > m;
char s[10000];
string a, b;
int main ()
{
scanf("%s", s);
//cin会保留\0,以后的输入必须getchar()
while(cin >> a>> b)
{
if(a == "END")
break;
m[b] = a;
}
getchar();
while(gets(s))
{
if(s[0] == 'E' && s[1] == 'N' && s[2] == 'D')
break;
string t;
int len = strlen(s);
for(int i = 0; i < len; i ++)
{
if(islower(s[i]))
t += s[i];
else
{
if(m.find(t) != m.end())
{
cout<< m[t];
}
else
{
cout<< t;
}
cout<< s[i];
t = "";
}
}
cout<< endl;
}
}