I am writing a program which takes .txt file, finds all words that end with a specific letter, puts them into another .txt. Then I have to sort new .txt in alphabetical order. I made the first work. When I try to sort after first cycle program crashes. I am totally new to input/output and vector functions so this code doesn't look pretty. My final plan is to make it into code with a bunch of functions.
* Might it be crashing because of constant opening/closing of .txt ?
* Too many for cycles makes it crash ?
UPDATE:
Cleared up the code, made it more readable and changed up few things. Works fine.
It could be the opening of the file inside your loops is causing problems, I suggest you just open your files once at the beginning of the functions.
Also look at this snippet:
1 2 3 4 5 6 7 8 9 10 11 12
for (int p=97; p<=122; p++){
// Kartoti pagal abc[] per visa abecele.
while (!input.eof()){
input >> line;
if (line.find(char (p)) == 0) myV.push_back(line);
}
//Surikiuoja vektoriu
for (int j=0; j< myV.size()-1; j++){
I doubt that the find function is doing what you expect. You may want to find the documentation for this function and pay attention to the return value, this function will only return zero if the specified letter is at the beginning of the string.
My intention was to filter .txt file with my chosen words for their first letters, put them into a vector, sort them inside and output it into new .txt file. if (line.find(char (p)) == 0) myV.push_back(line); Actually works by converting p (from 97 to 122, that is ASCII from a to z) to char and looking for it in the first position of my line. The only problem I am left with is that p doesn't change value inside this line for some reason while it does in other parts of the for loop. Tomorrow I will try to rewrite this program with functions instead of endless looping, I think it will work.
The problem is probably the fact that you are executing the while() until eof() is reached. eof() is an error condition, and once the stream fails no further processing can occur on that stream until the error state is cleared.
There are probably better ways of doing this instead of looping through the file again and again.
Also why are you using the int in your for loop, it would probably be clearer if you used a char instead.
1 2 3 4 5
for(char p = 'a'; p <= 'z'; ++p){
...
// if(line.find(p) == 0)
// This would probably be more self explanatory.
if(line[0] == p)
Also I recommend you start using the C++ style casts instead of the C style casts.