+ 1
Can someone recover this code ?
I can not understand how can check a and b to print them the screen ? https://code.sololearn.com/cMg1WqhqJS7C/?ref=app
21 Antworten
+ 5
#include <stdio.h>
int compareString(char *first, char *second) {
	int a = 0, b = 0, result = 0;
	while (*first != '\0') {
		first++; // just address increment
		a++;
	}
	while (*second != '\0') {
		second++; // just address increment
		b++;
	}
	if (a == b) {
		result = 0;
	}
	else if (a < b) {
		result = -1;
	}
	else if (a > b) {
		result = 1;
	}
	return result;
}
int main() {
	char first[1000],
		second[1000];
	printf("Enter your string :\n");
	gets(first);
	printf("Enter your string :\n");
	gets(second);
	switch (compareString(first, second)) {
	case -1:
		printf("first < second\n");
		break;
	case 0:
		printf("first == second\n");
		break;
	case 1:
		printf("first > second\n");
		break;
	}
	return 0;
}
Sample outputs:
Enter your string : aa
Enter your string : aaa
first < second
Enter your string : aaa
Enter your string : aa
first > second
Enter your string : aa
Enter your string : aa
first == second
+ 4
The length differences just count. It doesn't take into account the difference in letters. In fact the above function acts like std::string::compare() in C++.
https://en.cppreference.com/w/cpp/string/basic_string/compare
+ 3
It's possible, indeed.
+ 3
Enter your string :welcome
Enter your string :goodbye
The length of both strings is 7
But the letter `w` has higher ASCII value compare to `g`
So, first string > second string
Is this what you are looking for?
+ 3
You can simply replace the `printf`s texts with your favorite replacement like this:
switch (compareString(first, second)) {
case -1:
	printf("-1\n");
	break;
case 0:
	printf("0\n");
	break;
case 1:
	printf("1\n");
	break;
}
+ 3
Or even simpler
printf ("%d", compareString(first, second));
+ 3
Yes, because all you need to know is the integer result of the comparison, a single `printf` statement as above would be sufficient. It prints out
   `-1` when first < second
   `0` when first == second
   `1` when first > second
as simple as that.
+ 1
Thank both of youu 👍 :))
+ 1
Okey I will try thank you :))
0
Sorry donna I didn't kniw that my code's setting I edit it as a public but I think Babak has solved the problem
0
Does it work for just same characters or could it work for different ones ?
0
You wrote aa and aaa as an example it will work for jdhddj and jshdr ?
0
Can't we write this program in C ?This is my homework and I want to compare the letters of two words
0
Sample output:
Enter your string :welcome
Enter your string :goodbye
O  
Like this
0
No just number of letters
0
When the two word are equal number of letters I wanna print them to screen 0
0
When the number of first word greater than second I wanna print them to screen 1
0
When the number of second word greater than first one I wanna print to screen -1
0
Could I explain ?
0
If I change switch case section as this it will be true ?



