0

I'm trying to keep the alphabet in a char array. But 4 letters show absurd charachters.

I run the program step by step using F11 button. Wrote the alphabet and after 'Q', until 'V' whatever I write, it shows ...PQÿÿÿÿVWXYZ this character: 'ÿ'

    int main()
    {   
    cout << "ALPHABET:";
    char alf[] = "";
    cin >> alf;
        system("PAUSE");
    }

I expect: ABCDEFGHIJKLMNOPQRSTUVWXYZ

Actual result: ABCDEFGHIJKLMNOPQÿÿÿÿVWXYZ

0

1 Answer 1

1

Problem is with this line:

char alf[] = "";

you declare char array with size 1 which can only hold empty strings (null terminator). Note that std::istream::operator>> with char * does not validate size of array (it cannot) so you are getting Undefined Behavior writing into array with out of bounds. Solution is to use std::string instead which will grow as needed.

int main()
{   
    std::cout << "ALPHABET:";
    std::string alf;
    std::cin >> alf;
    std::cout << alf << std::endl;
}
Sign up to request clarification or add additional context in comments.

10 Comments

It probably should be at least 27 as you need null terminator, but I would not recommend to use char array with >> as it leads to unsafe programs that vulnerable to buffer overflow, do not make such habit.
I have a function which has a parameter char*. So I can't use string
@Slava - correction. It (operator>>) could have a separate overload for C-style arrays. It doesn't, though.
@ÖmerFarukSarıışık you should be able to use std::string and pass those functions the pointer to underlying char buffer you can get with c_str()
@SergeyA even with that overload it would only work in some cases, anyway lets say it cannot in the form it is written.
|

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.