说来实在是惭愧,学习acm也有将近一年了,虽说大多数时间都没干实事,但是连gets都不会用,简直不知道自己到底在干什么。。。
百科定义:
gets函数,可以无限读取,不会判断上限,以回车结束读取,所以程序员应该确保buffer的空间足够大。
gets从stdin流中读取字符串,直至接受到换行符或EOF时停止,并将读取的结果存放在buffer指针所指向的字符数组中。换行符不作为读取串的内容,读取的换行符被转换为NUL值,并由此来结束字符串。
头文件:stdio.h(c),cstdio(c++)
原型:char*gets(char*);
以前做法:
以前不知道用gets,所以总是自己写函数来读入
#include <cstdio>
#include <conio.h>
char String[105];
int tot;
void getstring()
{
char ch;
tot=0;
while(1)
{
ch=getchar();
if(ch=='\n'||ch==EOF)
{
return;
}
if(ch=='\b')
{
tot--;
continue;
}
String[tot++]=ch;
}
}
现在只要一个gets(String);
注意事项:
如果gets函数的前面还输入了其他东西,就要注意可能回车会留在键盘缓存区里,所以我就想了个傻办法,至于正宗方法还请大神赐教
char ch;
int n;
while(scanf("%d",&n)!=EOF)
{
scanf("%c",&ch);
while(n--)
{
getstring();
}
}
例题:
题意:输入n个字符串,判断是否为回文串
代码:
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
bool isPalindrome(char String[])
{
int len=strlen(String);
int i,j;
for(i=0,j=len-1;i<=j;i++,j--)
{
if(String[i]!=String[j])
return false;
}
return true;
}
int main()
{
char String[105],ch;
int n;
while(cin>>n)
{
scanf("%c",&ch);
while(n--)
{
gets(String);
if(isPalindrome(String))
cout<<"yes"<<endl;
else
cout<<"no"<<endl;
}
}
}
题意:统计字符串中元音个数,但是多组数据答案要最后一起输出
代码:
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
char String[100];
char ch;
int n;
int num[105][105]={0};
scanf("%d",&n);
scanf("%c",&ch);
for(int i=0;i<n;i++)
{
gets(String);
for(int j=0;String[j];j++)
{
switch(String[j])
{
case 'a': num[i][1]++;break;
case 'e': num[i][2]++;break;
case 'i': num[i][3]++;break;
case 'o': num[i][4]++;break;
case 'u': num[i][5]++;break;
default: break;
}
}
}
for(int i=0;i<n;i++)
{
printf("a:%d\n",num[i][1]);
printf("e:%d\n",num[i][2]);
printf("i:%d\n",num[i][3]);
printf("o:%d\n",num[i][4]);
printf("u:%d\n",num[i][5]);
if(i!=n-1)
printf("\n");
}
return 0;
}
题意:判断字符串是否是c的合法标识符(即由字母、下划线、数字这三个方面组成,但开头必须是字母或下划线,且关键字不能作为标识符)
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
bool isvalid(char c)
{
if((c>='a'&&c<='z')||(c>='A'&&c<='Z')||(c>='0'&&c<='9')||c=='_')
return true;
else
return false;
}
int main()
{
char string[105];
int n;
while(scanf("%d",&n)!=EOF)
{
char ch;
scanf("%c",&ch);
while(n--)
{
int flag=1;
int i=0;
scanf("%c",&ch);
if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z')||ch=='_')
flag=1;
else
flag=0;
while(1)
{
scanf("%c",&ch);
if(ch=='\n')
{
break;
}
if(isvalid(ch)==0)
flag=0;
}
if(flag)
cout<<"yes"<<endl;
else
cout<<"no"<<endl;
}
}
return 0;
}
题意:将英文句子的每个单词首字母变大写
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
char String[105];
while(1)
{
memset(String,0,sizeof(String));
gets(String);
int len=strlen(String);
if(len==0)
break;
bool first=1;
for(int i=0;String[i];i++)
{
if(first&&String[i]!=' ')
printf("%c",String[i]+'A'-'a');
else
printf("%c",String[i]);
if(String[i]==' ')
first=1;
else
first=0;
}
printf("\n");
}
return 0;
}