2017-06-29 27 views
-1

如果我給變量sa可變我不能能夠給輸入我得到運行時錯誤,我不能夠得到兩個char值A和B

#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; 
} 
+0

'%c'需要一個地址。你傳給它一個字符。使用:'scanf(「%c」,&a);''。注意's'是可以的,因爲數組會衰減到指向其第一個成員的指針。 –

+0

要讀取字符串,請使用:'scanf(「%s」,s) ;' –

+0

請問您能告訴我們這個程序應該做什麼嗎? –

回答

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; 
} 
0

當掃描字符,字符修改之前使用的白色空間,並通過焦炭爲指針,而不是價值。要掃描整個字符串,請使用修改後的%s。在這種情況下,您不需要編寫&s,因爲s本身已經包含數組的內存地址。如果您仍想使用&盈方,請使用&s[0],因爲&s[0] == s

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