我遇到运行时错误,我无法获得两个字符值 a 和 b



如果我为变量sa输入'Hello',则可以给输入

#include<stdio.h>
#include<string.h>
int main(){
    char s[100],a,b;
    //i am not able to get this value,please help me how to get three variables s,a,b at runtime
    scanf("%c",s);
    scanf("%c",a);
    scanf("%c",b);
    int n=strlen(s),count=0;
    for(int i=0;i<n;i++){
        if(s[i]==a && s[i+1]== b)
            count++;
    }
    printf("%d",count);
    return 0;
}

首先尝试使用 scanf("%c",&a) scanf。然后仅使用一个scanf读取三个变量。尝试此程序将解决您的问题:

#include <stdio.h>
#include <string.h>
int main()
{
    char s[100], a, b;
    //i am not able to get this value,please help me how to get three variables s,a,b at runtime
    scanf("%s %c %c", s, &a, &b);
    int n = strlen(s), count = 0;
    for(int i = 0; i < (n - 1); i++){
        if(s[i] == a && s[i+1] == b)
            count++;
    }
    printf("%d",count);
    return 0;
}

扫描字符时,使用字符修饰之前的空白空间,然后将char作为指针,而不是价值。对于扫描整个字符串,请使用修改的%s。在这种情况下,您无需编写&s,因为s本身已经包含数组的内存地址。如果您仍然想使用& Infront,请使用&s[0],因为&s[0] == s

char s[100], a, b;
scanf("%s", s);
scanf(" %c", &a);
scanf(" %c", &b);

最新更新