#include "stdafx.h"
#include <iostream>
#include <string>
#include <locale>
usingnamespace std;
int IndexOf(string& text, string& pattern)
{
// where appears the pattern in the text?
string::size_type loc = text.find(pattern, 0);
if (loc != string::npos)
{
return loc;
}
else
{
return -1;
}
}
int main(array<System::String ^> ^args)
{
string s = "Text";
// returns 1 because 'ext' is on the position 1 in s
int index = IndexOf(s, "ext");
// returns -1 because 'ABC' is not in s
int index = IndexOf(s, "ABC");
// returns 2 because 'xt' is on the position 2 in s
int index = IndexOf(s, "xt");
cin.get();
return 0;
}
Getting an error on the "ext", "ABC" and "xt" bits. It's basically giving me one of those underlined red squiggly lines and I'm not sure why it is happening.
Also, what is "string::size_type" used for as well as "string::npos" used for in this code?
#include <iostream>
#include <string>
usingnamespace std;
int IndexOf(string& text, string& pattern)
{
// where appears the pattern in the text?
string::size_type loc = text.find(pattern, 0);
if (loc != string::npos)
{
return loc;
}
else
{
return -1;
}
}
int main()
{
string s = "Text", pattern="ext";
// returns 1 because 'ext' is on the position 1 in s
int index = IndexOf(s, pattern);
cout<<index<<endl;
pattern="ABC";
// returns -1 because 'ABC' is not in s
index = IndexOf(s, pattern);
cout<<index<<endl;
// returns 2 because 'xt' is on the position 2 in s
pattern="xt";
index = IndexOf(s, pattern);
cout<<index<<endl;
return 0;
}
The major thing my compiler found are that you redeclare index on your lines 30 and 33, and "
Line 26: error: invalid initialization of non-const reference of type 'std::string&' from a temporary of type 'const char*'".