program crashes for no apparent reason

Hello. I made a C program that should show how many times a letter is contained by a text. I run it and after I cin>> the letter the program crashes. Any ideas why?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <stdio.h>

void main ()

{
    char c, txt[70];
    scanf("%c",c);
    scanf("%70c",txt);
    int i=0,nr=0;
    while(i<70)
    {
        if(c==txt[i])
        nr++;
        i++;
    }
    printf("%d",nr);
}
Change these statements

scanf("%c",c);
scanf("%70c",txt);

to


scanf("%c", &c);
scanf("%69s",txt);
Thanks. It doesn't crush anymore. Now I have to fix the letter counting part. I get random results.
Change the code

1
2
3
4
5
6
7
8
    int i=0,nr=0;
    while(i<70)
    {
        if(c==txt[i])
        nr++;
        i++;
    }
    printf("%d",nr);


to

1
2
3
    int i=0;
    while( txt[i] && txt[i] != c ) i++;
    if ( txt[i] ) printf("%d",i);
Last edited on
I am sorry. It seems that I showed incorrect code if you need to count letters that are equal to a given letter.

If you need to count letters then use the following code

1
2
3
4
5
6
7
    int count = 0;
    for ( int i = 0; txt[i] ; i++ )
    {
        if ( txt[i] == c ) count++;
    }
  
    printf( "%d", count );
Last edited on
Topic archived. No new replies allowed.