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

char* char2str(char);       //convert single char to null terminated string

int main()
{
    vector<string> dict;
    ifstream in("dictionary.txt");
    char *temp, ch;
    int i=0;
    while(in)
    {
             temp = new char[5];
             while(i<4)
             {
                       in.get(ch);
                       if(ch>='a' && ch<='z')
                       {
                                
                                strcat(temp, char2str(ch));
                                 i++;
                       }
             }
             dict.push_back(temp);
             i=0;
             delete temp;
    }
    
    
    for(int k=0; k<dict.size()-1; k++)
    cout<<dict[k]<<endl;
    system("PAUSE");
    return 0;
}

where the function chsr2str is

char* char2str(char c)
{
      char *str = new char[2];
      str[0] = c;
      str[1] = '\0';
      return str;
}

the output of this program is

trap
game
?=frog
€?=plan
beam
grim
list
bane
span
true
Press any key to continue . . .

please tell me why do i get those characters before the 3rd and 4th words.
thank u

Why not make life easier on yourself you're shifting between strings and char * unnecessarily. Change temp to a std::string and change line 9 to while (in >>temp) (letting that drive the loop) and you can eliminate lines 11-21 and 23-24.

Also on line 28 you don't need the -1, you'll miss your last element that way because you are using < instead of <=

thanks a lot jonsca, that really helped
one last question
if i make temp an std::string, j<dict.size() in final for loop works fine
but if i use char * throughout, j<dict.size() gives an extra row of all e's in output

It might have been reading the last e in "true" multiple times. I'm not sure, though.
Even working with the char * I wouldn't have read it in character by character I would have used getline and have the in.getline() statement drive the loop.
I would just stick with the std::string and then you don't have to worry about any of it.

Edited 6 Years Ago by jonsca: n/a

This article has been dead for over six months. Start a new discussion instead.