hi
i have a file dictionary.txt which contains a list of four-letter words which i have to read into a string vector.
i have written the following code
At line 11 you are dynamically allocating memory for 5 characters. After this is executed, temp points to the first of 5 characters in memory, which have not been initialised (i.e. they contain junk values).
What I think you want to do is replace the 'junk' values at index of temp by the character that you read:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
while(in)
{
temp = newchar[5];
while(i<4)
{
in.get(ch);
if(ch>='a' && ch<='z')
{
// Put the character at position 'i' in temp
temp[i] = ch;
i++;
}
}
// Don't forget to add the null string-terminating character!
temp[4] = '\0';
dict.push_back(temp);
i=0;
delete temp;
}
That worked for me. Also, if you know in advance that you're only dealing with 5-character arrays of chars, you don't have to dynamically declare it. It's faster and more efficient in this case to just statically declare it:
char temp[5];
Also note that if your file contains 4-letter words with capital letters you will get unintended behaviour. Consider what you can do to fix this.
thanks a lots sammy34 and Duoas, both methods work perfectly fine
however in sammy34's code i have to use j<dict.size()-1 in final for loop and in Duoas' code i have to use just j<dict.size()
using j<dict.size() in first method gives an extra row of e's in output
why is this so?
Because Duoas' code is better than mine :). In Duoas' code, note that the while loop will terminate when there is no more to read in the file. In my/your code, we go once more through (adding another element to dict as we go) because we read from the file INSIDE the while loop. I hope I explained that well enough...