cannot get substring from main string

//my first programming project
#include <iostream>
using namespace std;

int main ()
{
string thanos, ultron;
int rogers, stark, logan, i;
logan = 0;
i = 0;

do
{
rogers = 0;
stark = 0;
cout << "please enter the first string: ";
cin >> thanos;
for (i = 0; thanos [i] != '\0'; i++)
rogers++;
cout << "the length of the first string is: " << rogers << endl;
cout << "please enter the second string: ";
cin >> ultron;
for (i = 0; ultron [i] != '\0'; i++)
stark++;
cout << "the length of the second string is: " << stark << endl;
; }
while (stark > rogers);
if (thanos [i] == ultron [i])
if (logan == 0) cout << "the position of the substring is: ";
cout << i << " ";
if (logan != 0);
else
cout << "the substring was not found";
logan++;
i++;
return 0;
}
this is my new code with which I tried adding the functions for determining the position of the substring if the second string matches any part of the first string and if not the computer would instead output nothing was found. this piece of code has some errors I cannot figure out...for one the computer would always output the length of the second string a second time and then output nothing was found...any suggestions?
Hiya,
1. i don't see any functions in there. Do you mean that this is the code before you tried to do that?
2. Having a semi-colon at the end of an if is bad, like you've done here:
 
if (logan != 0);

the correct structure would be something like this:
1
2
3
4
5
6
7
8
	if (logan != 0)
	{
		// do something
	}
	else
	{
		// else do something else
	}


3. Incrementing variables at the end of your main function doesn't really do anything as your program is about to terminate, so:
1
2
logan++;
i++;


before your 'return 0' isn't doing anything.

4. You can't read into a string like this:
cin >> thanos;
take a look here:
http://www.cplusplus.com/reference/string/string/getline/

(and add #include<string> at the top of your code as well)

5. You have a loop that seems to increment 'rogers' and 'stark', which is okay BUT then at the start of the next loop you reset these variables to zero again, so they will not increment. Better to initiliase these variables outside the loop like you're done with 'logan' and 'i'.

6. to find the length of a string simply do something like this:
 
int strLength = thanos.size();

no need for those incrementing for loops.
Last edited on
wow, cant believe I made such a simple mistake with the semicolon. actually I should have made it clear, but in my code im trying to get the lengths of the strings without using any built in functions such as strlength() which is making it harder for me
Topic archived. No new replies allowed.