#include <stdio.h> int main() { char s[10]; char *p, ch; scanf("%s\n", s); ch = getchar(); if (ch == '\n') ch = getchar(); //处理输入回车的情况 p = s; while(*p != '\0') { if(*p == ch) { printf("Yes"); break; } p++; } if(*p == '\0') { //遍历完所有字符都没有找到 printf("No"); } return 0; }
时间: 2024-03-14 17:44:08 浏览: 18
这是一份可以正确处理输入回车的代码,完整代码如下:
```c
#include <stdio.h>
int main() {
char s[10];
char *p, ch;
scanf("%s\n", s);
ch = getchar();
if (ch == '\n') ch = getchar(); //处理输入回车的情况
p = s;
while(*p != '\0') {
if(*p == ch) {
printf("Yes");
break;
}
p++;
}
if(*p == '\0') { //遍历完所有字符都没有找到
printf("No");
}
return 0;
}
```
相关问题
#include <stdio.h> int main() { char ch=' '; scanf("%c",ch); while(ch != '\n') { if('a'==ch) { ch=='*'; } printf("%c",ch); } return 0; }
这段代码存在一些问题:
1. 在调用scanf函数时,需要传递ch变量的地址,即&ch,否则会导致程序崩溃。
2. 在if语句中,应该使用赋值运算符=而不是相等运算符==,否则无法将ch赋值为*。
3. 在while循环中,需要再次调用scanf函数,否则会导致死循环。
下面是修正后的代码:
```c
#include <stdio.h>
int main() {
char ch=' ';
scanf("%c",&ch);
while(ch != '\n') {
if('a'==ch) {
ch='*';
}
printf("%c",ch);
scanf("%c",&ch);
}
return 0;
}
```
修正后的程序可以将输入的字符串中的所有a替换成*并输出。
#include <stdio.h> #include <stdlib.h> int main() { int num,size,target,max=0; scanf("%d",&num); char *ch[num]; for(int i=0;i<num;i++){ scanf("%s",ch[i]); size=strlen(ch[i]); if(max==0){max=size;target=i;} else if(size>max){max=size;target=i;} } printf("%s",ch[target]); }问题在哪
这段代码的问题在于使用了未初始化的变量`target`,这可能导致程序输出错误的结果。
在代码中,变量`target`被用来记录输入的字符串中长度最长的字符串的下标。在代码的for循环中,如果当前输入的字符串长度比之前记录的最大长度还要大,就更新`max`和`target`变量。但是,在第一次比较时,如果输入的第一个字符串长度为0,那么变量`max`和`target`都会被赋值为0,而这个值可能不是最长字符串的下标,导致程序输出错误结果。
要解决这个问题,可以在定义变量`target`时,将其初始化为-1,表示还没有记录最长字符串的下标。然后在比较字符串长度时,如果当前字符串长度比最大长度还要大,就更新`max`和`target`变量。最后判断一下`target`的值是否为-1,如果不是,就输出最长字符串。
修改后的代码如下:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
int num, size, target, max = 0;
scanf("%d", &num);
char *ch[num];
for (int i = 0; i < num; i++) {
ch[i] = (char*)malloc(sizeof(char) * 100); // 为每个指针分配100字节的内存空间
scanf("%s", ch[i]);
size = strlen(ch[i]);
if (size > max) {
max = size;
target = i;
}
}
if (target != -1) {
printf("%s", ch[target]);
}
return 0;
}
```
这样就可以避免使用未初始化变量导致的问题。