// printing the words in the file.
for(iter = v.begin();iter!=v.end();iter++)
{
cout<<*iter<<endl;
}
system("pause");
return 0;
}
//example.txt
This file is written manually.
output :
This
file
is
written
manually.
manually.
I don't know why "manually" is printed twice at last. How to avoid it.
Also , to compare two words I think i have to use iterators and compare() in string class. I don't know how to do that . can any one help with code.
Thanks in advance.
I don't know why "manually" is printed twice at last. How to avoid it.
It's printed twice because you don't check to see if your input operation failed. When it does fail, you push the previous word onto the stack again.
1 2 3 4 5
while ( myfile2.good() )
{
myfile2 >> text ;
v.push_back(text) ;
}
should be:
1 2
while ( myfile2 >> text )
v.push_back(text) ;
You do not necessarily need to use iterators or compare() in your code. You can acess the individual members of v with the subscript operator (v[i]) and the comparison operators are overloaded for std::string so if ( v[i] > v[i+1] ) works as expected. Note valid indexes for v are from 0 to v.size()-1.
Please put code tags [code] [/code] around you code next time. It makes it much easier for us to read your code and therefore much easier to help.
Why is text not a std::string? Now your program will not work properly if for some reason one of the words in the file is more than 9 characters, so it's much safer to use std::string.
To compare two words you can use == if at least one of the words is an std::string.
The code is adding the last word twice because when the whole file has been read myfile2.good() still returns true. Not until after a read operation has failed, myfile2.good() will return false. So when when myfile2>>text; fails you still add the string to the vector on the line that follows. The correct way is to change the inner loop to something like this