Chinmaya
Chinmaya

Reputation: 11

Why is my terminal producing a beep sound whenever I am printing characters for C++ code?

I am a beginner in Programming in C++. Recently in my C++ Book there was a quick exercise to print a set of characters from a to z. I typed the following code in Visual Studio 2019.

char alphabet = 0;
    
while (alphabet < 130)
{
    cout << char(alphabet + 1)<<"\n";
    ++alphabet;
}

I can understand why my code prints weird characters and signs, because I have chosen ASCII characters valued from 1 to 130. However, the real problem is that my terminal produces a beep sound every time, even after all the characters are printed. I know for a fact that a beep sound is part of the ASCII character set, but it is only the character 7. But in my case the terminal produces a beep sound continuously until I kill the executable from the task manager. Please tell me the reason why there is a problem like this and please do not have a problem saying that this code is printing more than a to z. I just chose a random number so that I get the characters a to z in the terminal. I am running this code on Windows 7, so if the OS has something to do with it please tell.

Upvotes: 1

Views: 744

Answers (1)

Yun
Yun

Reputation: 3812

This condition

while (alphabet < 130)

always evaluates to true, because the char type typically has a range from [-128, 127]. When alphabet has the value 127 and is incremented by 1, it will wrap around and have the value -128. Therefore, your program tries to - somehow - print all these values. The positive ones correspond to ASCII values, where the value 7 instructs the terminal to beep.

Upvotes: 6

Related Questions