简体   繁体   中英

C Builder (C++) AnsiString Length method

I am used to program in c#, but now i had to help my roommate with a c++ project.

This is the "not working code" :

void  HighlightKeyWords::Highlight(TRichEdit eMemo,TRichEdit RichEdit1)
{
           ifstream file("KeyWords.txt");
           AnsiString temp;
           int maxWordLength=0;
           if(file.is_open())
        {
            while(file>>temp)
            {       if(temp.Length()> maxWordLength)
                    {
                            maxWordLength=temp.Trim().Length();
                    }
                    keyWords.push_back(temp);

            }
            file.close();
       }
       else
       {
            ShowMessage("Unable to open file. ");
       }
       for(unsigned i=0;i<KeyWords.size();i++)
       {
            richEdit1->Text=KeyWords[i];
       }
        eMemo->Text=MaxWordLength;
}

I get a list of keywords from the file. In MaxWordLength i want to know to maximum length of a word ( words are separated by new line in the text file ). When I do the temp.Length, i get 695 ( the number of all characters in the file ). Why am I not getting the actual length of the word i am adding to the vector?

Thank you!

LE: I also did the MaxWordLength logic in the for below, the for where i put the items in the RichEdit.

Use file.getline() instead of the >> operator, which won't produce the desired output in your case, but gives you the full file content as result. So AnsiString().Length() is not your problem. Just modify part of your code to get it working as intended:

char buffer[255];

if(file.is_open()){
    while(file.getline(buffer, sizeof(buffer))){
        temp = AnsiString(buffer).Trim();
        if(temp.Length()> maxWordLength) maxWordLength=temp.Length();
        keyWords.push_back(temp);
    }
    file.close();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM