Hello.
I recently started out with C++ and I was going to make a piece of code compare a letter in a text string to a specific letter, Now I have made a code that can do this, but it has some problems that I'm sure you will understand when you see it :
The program prints what I want it to:Code:#include <iostream> using namespace std; int main() { char *text_string = "abcddcba"; char *compare = "aaaaaaaa"; char *compare1 = "bbbbbbbb"; char *compare2 = "cccccccc"; char *compare3 = "dddddddd"; int Length = strlen(text_string); for (int i = 0; i < Length; ++i){ if(text_string[i] == compare[i]){ cout <<i+1<< "=a"<< endl; }else if(text_string[i] == compare1[i]){ cout <<i+1<< "=b"<< endl; }else if(text_string[i] == compare2[i]){ cout <<i+1<< "=c"<< endl; }else if(text_string[i] == compare3[i]){ cout <<i+1<< "=d"<< endl; } } cout << "Length of text is: " << Length; cin.get(); return 0; }
1=a
2=b
3=c
etc.
Now the problem is that if I use this code my compare variables must be over 20 letters long.
int compare = "20xa".
Before I got this code to even work I tried this code that would have been alot better:
But ofcourse that didnt work.Code:#include <iostream> using namespace std; int main() { char *text_string = "abcddcba"; int Length = strlen(text_string); for (int i = 0; i < Length; ++i){ if(text_string[i] == "a"){ cout <<i+1<< "=a"<< endl; }else if(text_string[i] == "b"){ cout <<i+1<< "=b"<< endl; }else if(text_string[i] == "c"){ cout <<i+1<< "=c"<< endl; }else if(text_string[i] == "d"){ cout <<i+1<< "=d"<< endl; } } cout << "Length of text is: " << Length; cin.get(); return 0; }
If anyone have any better solution to this I would appreciate if you could post it here.
ps: I hope you understand what I mean, my english isnt the best.



LinkBack URL
About LinkBacks



