0

If I add arr(1)=HelloWorld, It Works!

but If I add arr(1)=Hello,world or Hello_World or Hello World

It Doesn't!

A snippet of my code is enclosed below:

void CMFCApplicationFileDlg::OnClickBtnToData()
{

CString dataIn;
m_txtDataInput.GetWindowTextW(dataIn);  
int dem = 0;
int check = 0;
CString mangMaHoa[] = { _T("A"), _T("B"), _T("C"), _T("D"), _T("E"), _T("F"), _T("G"), _T("H"), _T("I"), _T("J"), _T("K"), _T("L"), _T("M"), _T("O"), _T("P"), _T("Q"), _T("R"), _T("S"), _T("T"), _T("U"), _T("V"), _T("W"), _T("X"), _T("Y"), _T("Z") };
int num = arr[1].GetLength();
CString mahoa, chuoiSauMaHoa;

for (int i = 0; i < arr[1].GetLength(); i++)
{
    mahoa = arr[1].Mid(i, 1);
    dem = 0;
    check = 0;
 
        for (int j = 0; j < 26; j++)
        {
            if (mangMaHoa[j].CompareNoCase(mahoa) == 0)
            {
                check += 1;
                if (j >= 23)
                {
                    dem = j + 3;
                    dem = dem - 26;
                }
                else
                {
                    dem = j + 3;

                }
                chuoiSauMaHoa += mangMaHoa[dem];
                break;
            }
            else
            {

                continue;
            }
        }
        if (check == 0)
        {
            chuoiSauMaHoa += mahoa;
        }       
}
m_txtDataOutput.SetWindowTextW(chuoiSauMaHoa);

}

if (check == 0)
{
    chuoiSauMaHoa += mahoa;
}   

I wish to get all characters

Screenshot:

Screenshot:

Thanks in advance!

1
  • Your code is not explicit about what arr is. Commented Jul 13, 2015 at 22:34

1 Answer 1

1

You're relying a lot on the magic number 26 which you presume to be the length of your array mangMaHoa.

However it's actually of length 25 (did you intend leaving out letter N?)

So out-of-bounds errors are going to happen especially when searching for your special characters ,, _ and space.

Instead of presuming what you think to be the size of the array you should be defensive and determine the actual size of the array

size_t alphabet = sizeof(mangMaHoa) / sizeof(mangMaHoa[0]);

and use the result instead.

Sign up to request clarification or add additional context in comments.

1 Comment

A safer version for your expression would be _countof. It fails to compile should the argument be a pointer rather than an array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.