tags:

views:

159

answers:

7

Hi, How to make the hardware beep sound with c++?

Thanks

A: 

Here's one way:

cout << '\a';

From C++ Character Constants:

Alert: \a

Ani
+1  A: 

Easiest way is probbaly just to print a ^G ascii bell

Martin Beckett
`stdout`, perhaps? There's no object named `out` in `namespace std`.
Ben Voigt
sorry typo - thanks
Martin Beckett
A: 
std::cout << '\7';
PigBen
+7  A: 
cout << '\a';

Source

:)

djechelon
+6  A: 

If your using Windows OS then theres a function called Beep()

#include <iostream> 
#include <windows.h> // WinApi header 

using namespace std;

int main() 
{ 
    Beep(523,500); // 523 hertz (C5) for 500 milliseconds     
    cin.get(); // wait 
    return 0; 
}

Source: http://www.daniweb.com/forums/thread15252.html

For Linux bassed OS theres:

echo -e "\007" >/dev/tty10

And if you do not wish to use Beep() in windows you can do:

echo "^G"

Source: http://www.frank-buss.de/beep/index.html

RobertPitt
That's not standard C++. We don't even know if he's using Windows.
Ben Voigt
Operating system was never mentioned in question or tags
Samuel
Im not a C++ programmer, C# mainly but thought that resource would of been helpful, Dont think it was worth a down-vote but that's your prerogative
RobertPitt
A: 

The ASCII bell character might be what you are looking for. Number 7 in this table.

typoknig
+2  A: 

There are a few OS-specific routines for beeping.

  • On a Unix-like OS, try the (n)curses beep() function. This is likely to be more portable than writing '\a' as others have suggested, although for most terminal emulators that will probably work.

  • In some *BSDs there is a PC speaker device. Reading the driver source, the SPKRTONE ioctl seems to correspond to the raw hardware interface, but there also seems to be a high-level language built around write()-ing strings to the driver, described in the manpage.

  • It looks like Linux has a similar driver (see this article for example; there is also some example code on this page if you scroll down a bit.).

  • In Windows there is a function called Beep().

asveikau
'\a' is defined by the C++ standard, and is extremely portable. Of course if you're using broken terminal software all bets are off, but the Win32 console subsystem and most xterm clones all process '\a' properly.
Ben Voigt
@Ben Voigt: Correct me if I'm wrong, but the C++ standard only specify that '\a' will represent an ASCII BEL character; but it never specifies what the programs' behavior should be when sending such character to stdout. The part that ASCII BEL == '\a' is extremely portable, as you said, but the beeping part is a totally undefined behavior.
Lie Ryan
@Ben: as far as I'm concerned, terminal software is broken if it *doesn't* have a way of switching off the bell.
Steve Jessop
@Steve: I agree, but I don't read this question is "How do you make a beep when the users has explicitly turned sounds off?"
Ben Voigt