69,371
社区成员
发帖
与我相关
我的任务
分享
void main(){
char st[20],*ps;
int i;
printf("input a string:");
ps=st;
scanf_s("%s",ps);
for(i=0;ps[i]!='\0';i++)
if(ps[i]=='k'){
printf("there is a 'k' in the string\n");
break;
}
if(ps[i]=='\0')
printf("There is no 'k' in the string\n");
system ("pause");
//return 0;
}
ps=st;
代码的时候出现了错误,但是本身程序不报错,只是得不到正确结果#include <stdio.h>
#include <cstdlib>
void main(){
char st[20],*ps;
int i;
printf("input a string:");
scanf("%s",st);//改用scanf,直接给数据赋值
ps=st;//指针指向数组首地址
for(i=0;ps[i]!='\0';i++)
if(ps[i]=='k'){
printf("there is a 'k' in the string\n");
break;
}
if(ps[i]=='\0')
printf("There is no 'k' in the string\n");
system ("pause");
}
char st[20],*ps; //定义了一个数组, 以及一个指针
int i;
printf("input a string:");
ps=st; //数组名也等于一个指针, 赋值之后ps可以操作st这个数组的内容
scanf("%s",ps); //这里不要用scanf_s(); 不具备通用性, scanf()才是标准C的函数
for(i=0;ps[i]!='\0';i++) //for循环要加大括号, 否则第二个if不在for循环的作用域中
{
if(ps[i] == 'k'){
printf("there is a 'k' in the string\n");
break;
}
if(ps[i]=='\0')
printf("There is no 'k' in the string\n");
}
scanf_s("%s",ps);
这行代码改成scanf("%s",ps);
程序可以得出正确结果,但是依然会有一个安全警告,如果不喜欢可以改成scanf_s("%s",ps,20);
或者scanf_s("%s",st,20);
程序都可运行出正确结果
char st[20],*ps;
int i;
printf("input a string:");
ps=st;
scanf_s("%s",ps);
我觉得可以简化,没有必要再定义一个指针:
char ps[20];
int i;
printf("input a string:");
//scanf("%s",ps);
scanf_s("%s",ps,20);
#include <stdio.h>
#include <cstdlib>
void main(){
char st[20],*ps;
int i;
printf("input a string:");
ps=st;
//scanf("%s",ps);
scanf_s("%s",ps,20);
for(i=0;ps[i]!='\0';i++)
if(ps[i]=='k'){
printf("there is a 'k' in the string\n");
break;
}
if(ps[i]=='\0')
printf("There is no 'k' in the string\n");
system ("pause");
//return 0;
}
百度一下scanf_s,得知:很多带“_s”后缀的函数是为了让原版函数更安全,传入一个和参数有关的大小值,避免引用到不存在的元素,有时hacker可以利用原版的不安全性黑掉系统。比如:char d[20];写成scanf_s("%s",d,20);才是正确的,有这个参数20使准确性提高。
学习了~~~