【发布时间】:2014-03-08 17:56:56
【问题描述】:
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char a[10001],b[10001];
int tot,s1,s2;
cin>>tot;
while(tot!=0) {
gets(a);
gets(b);
s1= strlen(a);
s2= strlen(b);
cout<<s1<<s2<<endl;
tot--;
s1=0;
s2=0;
}
}
这是一个查找两个字符串长度的程序,还输入了大小写 输入:
4
abcd
xyz
abcd
bcda
aabc
acaa
Codechef
elfedcc
预期输出
43
44
44
87
但输出是
04
34
44
48
为什么?
【问题讨论】:
-
编译器正在惩罚你使用
gets(否则在cin>>tot;之后的输入缓冲区中仍然有一个换行符)。 -
请注意
gets即将被删除(libc++ 已经在其 C++1y 支持中这样做了)。 -
提示:使用
std::string,不需要1001大小的数组,另外,它有一个size()成员!
标签: c++ string-length