program crashes for no apparent reason
Jan 8, 2013 at 1:42am UTC
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);
}
Jan 8, 2013 at 1:48am UTC
Change these statements
scanf("%c",c);
scanf("%70c",txt);
to
scanf("%c", &c );
scanf("%69s ",txt);
Jan 8, 2013 at 2:03am UTC
Thanks. It doesn't crush anymore. Now I have to fix the letter counting part. I get random results.
Jan 8, 2013 at 2:08am UTC
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 Jan 8, 2013 at 2:09am UTC
Jan 8, 2013 at 2:34am UTC
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 Jan 8, 2013 at 2:34am UTC
Topic archived. No new replies allowed.