sVec strings;
sIter iter;
//Create a string for input.
std::string input;
//open a file to populate the vector.
std::ifstream iFile;
iFile.open( "VectorStrings.txt", std::ios::binary );
//Check if the file has opened.
if( iFile.is_open() )
{
//Populate the vector
/* Coded already */
}
else //iFile is NOT open
{
std::cout << "Unable to open a file to populate the vector.\nExiting...\n";
return;
}
//output a message to the user.
std::cout << "\n\nPlease enter a letter, to remove each word that contains it.\n";
//Get user input.
std::getline( std::cin, input, '\n' );
//Loop vector entrys.
for( iter = strings.begin(); iter != strings.end(); ++iter )
{
//Loop through each letter in the vector index.
for( unsignedint i = 0; i < ( iter->length() - 1 ); ++i )
{
//Check for a match.
if( input == iter[ i ] ) /* ERROR */
std::cout << "Letter found\n";
}
}
Above, on line 36, I only get an error when the last char is checked on the fourth vector index.
Below is the text file contents, that is populating the array.
Horse
Monitor
Bench
Cupboard //Error when 'd' is checked here.
Lamppost
Field
Watch
Running
Cloud
Building
Can anyone, please shed some light on why this error is/maybe happening? Any help is appreciated!
Thanks.
Edit: Also, this doesn't actually work! Forgot to add that, ahaha. This doesn't actually come up with any matched chars.
Typically that means you're trying to access an invalid iterator. It could be invalid for a couple reasons; std::vector::push_back() got called and it made the vector move somewhere else, or you've gone too far.
iter isn't a pointer or an indexable container, you can't use iter[i] at all. If it happens to compile and access the first few letters of your strings, it's a side effect of how your compiler implements strings and vectors.
Edit: er, forgot that randomaccessiterators do have operator[] defined. Anyway, the rest of this answer holds:
The expression to access the ith character of the string referenced by iter is (*iter)[i]
It would help to see a complete, compilable program, to give useful advice at this point, if if you're really looking for a letter (code suggests otherwise), use the string member find, as in if(iter->find(letter) != string::npos)
iter isn't a pointer or an indexable container, you can't use iter[i] at all. If it happens to compile and access the first few letters of your strings, it's a side effect of how your compiler implements strings and vectors.
It is possible to use operator[] on random access iterators. iter[i] is the same as *(iter + i).
Peter87, iter is a pointer to the iterator (Or a iterator to the pointer? Lol). So you needed (*iter)[i]. Well I don't have the exact strings info I needed but it looks like I got the problem and the answer.
@Lynx876 No problem ^
At your question over, yeah it looks like it is the same, unless strings is a pointer-to-string vector which caused the error above (in a slightly different manner).