问题来自pat乙级1033,错误代码如下
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main(){
string broken_keys, sentence;
cin>>broken_keys>>sentence;
bool shift = false;
if(broken_keys.find('+') != string::npos) shift = true;
for(int i=0; i<int(sentence.length()); i++){
if(isupper(sentence[i]) && shift) continue;
else if(broken_keys.find(toupper(sentence[i])) != string::npos) continue;
else cout<<sentence[i];
}
return 0;
}
用cin输入了两个string,提交代码在第二个测试点出错,改成用getline函数后就不会出错。
原因:测试点的输入第一行就是个空行,代表所有键都是好的,用cin接收不到空行
另外
1、istream类对运算符>>有两个重载,第一个是成员重载,第二个是非成员重载,后者在参数是字符、字符串类型的时候调用,第一个适用于其他int、bool等情况。
只有string头文件下的getline函数的参数才是string对象。推断用cin>>后面接string对象的时候,发生了string类向c风格字符串的类型转换。
2、getline()结束条件:遇到 delim 或 ‘\n’ 或EOF,并将其从输入流中取出丢弃,不会存起来。
cin>>会忽略开头的whitespace,而在结尾的whitespace处结束,将其留在输入流中
cstdio中的输入也类似,gets()遇到 ‘\n’ 或EOF结束,’\n’也会存起来,并在最后加上’\0’,pat不允许使用
scanf会忽略开头的whitespace,而在结尾的whitespace处结束,将其留在输入流中
用fgets()替换gets():
#include <cstdio>
char s[1000];
fgets(s, 1000, stdin); //最多读取999个字符,包括'\n'
//输入以换行符作为结束
for(int i=0; i<1000; i++){
if(s[i]=='\n'){
s[i]='\0';
break;
}
}