comparing characters of string c programming

Apr 2, 2013 at 12:46pm
how to compare each character of a string using "if " ,"string[i]" ("i" is a number of a sequence of hat string) c programming. the idea of the program is to give values to letters like a=1, b=2 and if i write a word in console "a,b,a,b" id get the sum of 1+2+1+2. and i want to compare each character of the string till the end of the string. something like that:


#include <stdio.h >
int main ()
{
char string[20];
char a, b;
int i;
int sum;
print f (" my word is:\n");
scan f ( "%s\n ", string);

sum1=1; sum2=2;
sum=0;

if (string[i]==a ) {sum= sum +sum1;} else
if (string[i]=='\0' ) {sum= sum +0;} else
{sum=0;}

while (i<=4)
{
i=i+1;
}

print f ("%d\n" , sum);
return 0;

}
this program crashes saying that ive not initialized "i"
Apr 2, 2013 at 1:18pm
This program doesn't compile because there's a space in the middle of the function names "print f" and "scan f". I'd recommend that the actual code is simply copy+pasted here.

As for the i not initialised, that also applies to variables a and b, while variables sum1 and sum2 are used without having been declared (is sum1 type char or double ...?).

It looks like the logic isn't really correct as well, but that's a separate issue.
Apr 2, 2013 at 1:27pm
this compares nothing ;) try this
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
using namespace std;
int main ()
{
char string[20];
cin.getline(string,sizeof(string));

int adda=1,addb=2,sum=0,i=0;
while (string[i]!='\0')
{
	switch (string[i])
	{
		case 'a':
			sum=sum+adda;
			break;
		case 'b':
			sum=sum+addb;
			break;
	}
	i=i+1;
}
cout << sum;
cin.ignore();
return 0;
}


written in c++, enjoy
Apr 2, 2013 at 2:07pm
Another version
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <string.h>
#include <stdio.h>

int main()
{
    char string[20];
    char letters[]  = "abcdef";

    printf (" my word is:\n");
    scanf ( "%19s", &string);

    int i = 0;
    int sum = 0;

    while (string[i])
    {
        char * p = strchr(letters, string[i]);
        if (p)
        {
            int pos = (p-letters) + 1;
            printf("Char %c found at position %d\n", string[i], pos);
            sum += pos;
        }
        i++;
    }

    printf ("%d\n" , sum);

    return 0;
}

See reference page for strchr() http://www.cplusplus.com/reference/cstring/strchr/
Topic archived. No new replies allowed.