### comparing characters of string c programming

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"
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.
this compares nothing ;) try this
 12345678910111213141516171819202122232425 #include 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
Another version
 123456789101112131415161718192021222324252627282930 #include #include 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.