-1

If I give input 'hello' for variable s and a for variable i cant able to give input

#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;
}
dbush
  • 205,898
  • 23
  • 218
  • 273
  • `%c` needs an address. You pass it a char. Use: `scanf("%c",&a);`. Note that `s` is OK as an array decays to a pointer to its first member. – Paul Ogilvie Jun 29 '17 at 16:00
  • To read a string, use: `scanf("%s",s);` – Paul Ogilvie Jun 29 '17 at 16:01
  • Could you please tell us what exactly this program is supposed to do? – Jabberwocky Jun 29 '17 at 16:01
  • Please [read this](https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-buffer) about `%c` format and newlines. – Weather Vane Jun 29 '17 at 16:03
  • input format: string value for variable s , second line to get charecter for variable 'a' and third line to get another charecter for variable 'b' but i cannot able to give input in proper manner – user7709640 Jun 29 '17 at 16:07

2 Answers2

0

First of all try to use scanf("%c",&a) scanf. Then read the three variables using just one scanf. Try this program it will resolve your problem:

#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;
}
P.A
  • 741
  • 4
  • 16
0

When scanning character, use white space before character modifier, and pass char as pointer, not as value. For scanning entire string, use modified %s. In this case, you don't need to write &s as s itself is already contain memory address of array. If you still want to use & infront, then use &s[0] because &s[0] == s.

char s[100], a, b;
scanf("%s", s);
scanf(" %c", &a);
scanf(" %c", &b);
unalignedmemoryaccess
  • 7,246
  • 2
  • 25
  • 40