Usage of \b and \r in C - c

\b and \r are rarely used in practice. I just found out that I misunderstood these two escape sequences. A simple test:
printf("foo\bbar\n");
I expected it to output fobar, because \b will backspace the cursor, and b will overwrite the second o, but instead it outputs: foobar
The same is with \r:
printf("foo\rbar\n");
I thought \r will move the cursor to the beginning of the current line, so bar will replace foo, so the final output should be bar. However, it actually outputs:
foo
bar

The characters will get send just like that to the underlying output device (in your case probably a terminal emulator).
It is up to the terminal's implementation then how those characters get actually displayed. For example, a bell (\a) could trigger a beep sound on some terminals, a flash of the screen on others, or it will be completely ignored. It all depends on how the terminal is configured.

The characters are exactly as documented - \b equates to a character code of 0x08 and \r equates to 0x0d. The thing that varies is how your OS reacts to those characters. Back when displays were trying to emulate an old teletype those actions were standardized, but they are less useful in modern environments and compatibility is not guaranteed.

The interpretation of the backspace and carriage return characters is left to the software you use for display. A terminal emulator, when displaying \b would move the cursor one step back, and when displaying \r to the beginning of the line. If you print these characters somewhere else, like a text file, the software may choose. to do something else.

As for the meaning of each character described in C Primer Plus, what you expected is an 'correct' answer. It should be true for some computer architectures and compilers, but unfortunately not yours.
I wrote a simple c program to repeat your test, and got that 'correct' answer. I was using Mac OS and gcc.
Also, I am very curious what is the compiler that you were using. :)

I have experimented many of the backslash escape characters. \n which is a new line feed can be put anywhere to bring the effect. One important thing to remember while using this character is that the operating system of the machine we are using might affect the output. As an example, I have printed a bunch of escape character and displayed the result as follow to proof that the OS will affect the output.
Code:
#include <stdio.h>
int main(void){
printf("Hello World!");
printf("Goodbye \a");
printf("Hi \b");
printf("Yo\f");
printf("What? \t");
printf("pewpew");
return 0;
}

In different compilers, backslash escape characters behave differently.
In MAC OS with clang \b takes off the last char from the console as you expected.
#include <iostream>
int main ()
{
std::cout << "Test";
std::cout << "\b";
std::cout << "\n";
return 0;
}
output:
Tes

Related

Why can't we print ASCII values from 0 to 31?

#include<stdio.h>
int main()
{
for(int i=0;i<=31;i++)
printf("%c",i);
}
when we try to run this code then nothing prints
what is the reason for it ?
C is printing them, but perhaps your terminal is not displaying them. This distinction is important because the terminal is responsible for interpreting the output of your program, printing letters, moving the cursor around, changing colors and such.
By historical convention the first 32 characters of the ASCII table are considered "control characters", some of which are printable, some like backspace which move the cursor, others like BEL which can make your terminal beep.
Different terminals may display these differently, or not at all.
It's worth noting that ASCII pre-dates modern "glass" terminals and that these codes were used to move the print-head around on the page. Early machines used teletypes to communicate with them and a line-feed would crank down the paper one line, a carriage return move the cursor back to the start of the line, much like the physical carriage return on a typewriter which would move the "carriage" back to the first column.
These were pretty elaborate elecromechanical contraptions that didn't have any modern circuitry in them, yet they could still process ASCII data, at least for those using ASCII, as there are other character sets like EBCDIC that co-existed with ASCII.
As these characters were never intended to be printed, so they don't have a standard visual representation in ASCII.
With "extended ASCII", as used in DOS, there are symbols defined for them because it seemed like a waste otherwise. These don't have control-code meanings, typically you write them directly to the console character buffer in order to see them.
You can, it's just that most of them are non-printable control characters that most shells ignore. If you pipe stdout to a file, the file will contain those characters, it's just the shell that doesn't know what to do with them. Some of them are handled by shells (e.g. the line feed and backspace characters) but others are just nonsensical (e.g. end of transmission, data link escape) and get ignored, or replaced with a different character for display (often a space or a question mark or the like).

Carriage return in c programming showing different output [duplicate]

\b and \r are rarely used in practice. I just found out that I misunderstood these two escape sequences. A simple test:
printf("foo\bbar\n");
I expected it to output fobar, because \b will backspace the cursor, and b will overwrite the second o, but instead it outputs: foobar
The same is with \r:
printf("foo\rbar\n");
I thought \r will move the cursor to the beginning of the current line, so bar will replace foo, so the final output should be bar. However, it actually outputs:
foo
bar
The characters will get send just like that to the underlying output device (in your case probably a terminal emulator).
It is up to the terminal's implementation then how those characters get actually displayed. For example, a bell (\a) could trigger a beep sound on some terminals, a flash of the screen on others, or it will be completely ignored. It all depends on how the terminal is configured.
The characters are exactly as documented - \b equates to a character code of 0x08 and \r equates to 0x0d. The thing that varies is how your OS reacts to those characters. Back when displays were trying to emulate an old teletype those actions were standardized, but they are less useful in modern environments and compatibility is not guaranteed.
The interpretation of the backspace and carriage return characters is left to the software you use for display. A terminal emulator, when displaying \b would move the cursor one step back, and when displaying \r to the beginning of the line. If you print these characters somewhere else, like a text file, the software may choose. to do something else.
As for the meaning of each character described in C Primer Plus, what you expected is an 'correct' answer. It should be true for some computer architectures and compilers, but unfortunately not yours.
I wrote a simple c program to repeat your test, and got that 'correct' answer. I was using Mac OS and gcc.
Also, I am very curious what is the compiler that you were using. :)
I have experimented many of the backslash escape characters. \n which is a new line feed can be put anywhere to bring the effect. One important thing to remember while using this character is that the operating system of the machine we are using might affect the output. As an example, I have printed a bunch of escape character and displayed the result as follow to proof that the OS will affect the output.
Code:
#include <stdio.h>
int main(void){
printf("Hello World!");
printf("Goodbye \a");
printf("Hi \b");
printf("Yo\f");
printf("What? \t");
printf("pewpew");
return 0;
}
In different compilers, backslash escape characters behave differently.
In MAC OS with clang \b takes off the last char from the console as you expected.
#include <iostream>
int main ()
{
std::cout << "Test";
std::cout << "\b";
std::cout << "\n";
return 0;
}
output:
Tes

Impossible to put stdout in wide char mode

On my system, a pretty normal Ubuntu 13.10, the french accented characters "éèàçù..." are always handled correctly by whatever tools I use, despite LC_ environment variables being set to en_US.UTF-8.
In particular command line utilities like grep, cat, ... always read and print these characters without a hitch.
Despite these remarks, such a small program as
int main() {
printf("%c", getchar());
return 0;
}
fails when the user enters "é".
From the man pages, and a lot of googling, there is no standard way to close stdout, then reopening it. From man fwide(), if stdout is in byte mode, I can't pass it to wide character mode, short of closing it and reopening it... therefore I can't use getwchar() and wprintf().
I can't believe that every single utility like cat, grep, etc... reimplements a way to manage wide characters, yet from my research, I see no other way.
Is it my system that has a problem? I can't see how since every utility works flawlessly.
What am I missing, please?
When a C program starts, stdout, stdin and stderr are neither byte nor wide-character oriented. fwide(stdin, 0) should return 0 at this point.
If you expand your minimal program to:
#include <stdio.h>
#include <locale.h>
#include <wchar.h>
int main()
{
setlocale(LC_ALL, "");
printf("%lc\n", getwchar());
return 0;
}
Then it should work as you expect. (There is no need to explicitly set the orientation of stdin here - since the first operation on it is a wide-character operation, it will have wide-character orientation).
You do need to use getwchar() instead of getchar() if you want to read a wide character with it, though.
UTF-8 character are taken as byte code not character and non ascii character are more then one byte.
Check this Question
for more info
The utilities you mention are generally line-oriented. If you were to try to read a whole line with e.g. fgets() rather than a single character, I think it'll work for you, too.
When you start reading single characters (which may be just bytes, and often are), you are of course very much susceptible to encoding issues.
Reading full lines will work just fine, as long as the line-termiation encoding is not mis-understood (and for UTF-8 it won't be).

Newline character in C other than \n? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
Is there a replacement of \n in C? Can I jump to next line without using \n? I came across this question and I cannot seem to figure out a way..
#include < stdio.h>
void main()
{
printf("A");
printf("B");
}
I want it to print
A
B
And not
AB
But I cannot use \n.
You can use puts("A"); puts("B");.
To output \n without writing \n you could simply printf("%c",10);, or char c=10;write(1,&c,1);, or 100 other ways to output ascii 10.
But if you would like to avoid the newline character completely, the answer varies. It's not C or your code that actually decides to go to a new line, but whatever the device is that displays your output.
E.g. a terminal, or a line printer, or a web browser showing html.
Suppose you are outputting to a browser, the answer would be <br>
If you are outputting to an xterm terminal, \033[1B moves the cursor one line down. The output a carriage return \r to move to the beginning of the line.
So for example:
printf("test\033[1B\r123");
will output (in an xterm)
test
123
As an alternative to puts(), you can use the octal equivalent of \n: \012.
E.g.
#include <stdio.h>
int main()
{
printf("A\012");
printf("B\012");
return 0;
}
\n means "new line". \rmeans "carriage return". These characters have their origin from old form-feed printers, which needed both, one to advance the paper to a new line, one to return the carriage with the print head to the start of the line.
Different OS-es have uses different combinations of the two to indicate a new line in text:
Unix (and Linux, Mac OSX, etc) uses only \n
Windows uses \r\n
Mac OS up to version 9 uses only \r
There is no canonical platform-independent way in the C standard libraries to represent the "System"'s newline/carriage return character. However, many other languages and/or libraries have implemented this, e.g:
Java: System.getProperty("line.separator")
.NET: System.Environment.NewLine
However, if you have an output stream open on a text file, the standard C libraries should translate \n to whatever is necessary to indicate a new line on the current system.
I'd simply use:
printf("A%cB",10);
In C the escape sequence \n represents a character that belongs to the basic execution character set.
In particular, one can be sure that a new-line character exists when our C programs are running.
More important: \n is mapped to 1 and only 1 character, whose code is a positive integer number in the range of the type char.
However, the behaviour of the display devices can produce other results.
For example, when we send a character \n to a text file under Windows, this is replaced by the sequence of two characters \x0D\x0A (LF+CR, that is: Line Feed + Carriage Return).
The standard C99 or C11 says:
(5.2.2) \n (new line) Moves the active position to the initial position of the next line.
The meaning of that (in every system that prints several lines in its standard display device), the "effect" of sending a character \n is "advance to the next line" and "go to the beginning of that line". It is the sum of "line feed" and "carriage return" operations.
In DOS/Windows this is equivalent to send the sequence of these two characters: '\xD', '\xA'.
In Linux/Unix this is equivalent to send the only character '\xD'.
More details here: http://en.wikipedia.org/wiki/Newline
Summarizing, we have to distinguish betwenn the character \n by itself, and the semantic related to \n when is considered as a control character in C.
You can "produce" a new line just by sending the character '\n' with putc() or printf().
By using \n is the better way to do that.
Another very good alternative is that pointed out by #1'': to use the function puts(str).
This function appends a new-line at the end of the string str.
I think is not at all a good idea to try this other alternatives:
printf("%c", 10); // 10 == 0x0A
printf("%c", 13); // 10 == 0x0D
printf("\x0A"); // CR
printf("\x0D"); // LF
You are not solving the problem properly, because your program becomes system dependent.
Valid for Windows, Linux or what?
Worst: in theory, the standard C does not ensures that you even have correspondence between the ASCII/Unicode code numbers for the characters and the characters used in the system your program will run. This issue involves to the control characters, too.
So, you cannot be sure that 0x10 means "carriage return" and 0x13 means "line feed".
To be sure of that, it is necessary to check the existence of the following macro:
__STDC_ISO_10646__
(That macro, if exists, is a long int number containing information about the version of Unicode supported by your compiler.)
The important thing is: if the macro __STDC_ISO_10646__ is not defined, you cannot have certainty about the codes assigned to the characters in your system.
Thus, it cannot be used the "magic numbers" 10 and 13.

This program sounds the bell!

I'm a brand-new student in programming arena so I can't grasp this program written in my book that I have been following for a few days. The program is like this:
#include "stdio.h"
main()
{
printf("\a");
}
What does this program mean? Does this program mean that we could hear a ringing bell? I can't hear any ringing bell sound!!!
ASCII character 7 is the BELL character, and it's represented in C as \a. Some terminals will produce a beep when this character is output on the terminal; nowadays, many don't. (I'm looking at you, Ubuntu.)
Back in the dark ages when ASCII was codified out of the ashes of BAUDOT, a terminal was a large chunk of iron that hammered ink onto paper, often included a paper tape punch and reader, and interpreted keystrokes to generate an asynchronous serial signal at a few hundred baud with spinning wheels and relays.
In case an operator fell asleep to the soothing noises of it hammering out text, it had an actual bell it could ring. The character coded 007 in octal, 0x07 in hex, or as \a in a C character or string constant rang the bell when received.
As terminals became smaller and implemented with few or no moving parts, the physical bell was replaced by a beeper.
Exactly what your terminal emulator (aka a Console Window in Windows, xterm or something similar in Unix) does when it is asked to display that control character is not well standardized today. It ought to make a noise or flash the window, but your mileage will vary.
Have a look at this wikipedia entry: bell character:
In the C Programming Language (created in 1972), the bell character can be placed in a string or character constant with \a ('a' stands for "alert" or "audible" and was chosen because \b was already used for backspace).
\a does in fact trigger the system chime. It's the escape sequence for the ASCII BEL character.
You'll hear a beep from your PC's internal speaker (not the external speakers or headphones you may have attached).
Strings can contain characters which are handled different from all the other characters. The most often explicit used one is '\n'. The '\n' character does not print a character in the console, instead it tells the console to start a new line. Such special characters are called non printable since they have no own visible representation in c and have to use escape sequences instead.
In the escape sequence "\a" the backslash before the a tells the compiler that the a is an identifier for a special character and will store its char-value instead of the char-value of 'a'.
The '\a' escape sequence is the audible bell character, giving this character to a console via print() should cause a beep sound. Some consoles wont beep.
Here are some special characters, the link is from a c++ reference but most should be valid for c.
\a is the C representation of the ASCII audible alert ("bell") control character.
On an old-school serial terminal, outputting that character produced a "beep" sound. Your terminal emulator may or may not implement this feature.
Apart from all the answers you've got, take into account that your program won't probably compile. Here is the fixed version:
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("\a");
return EXIT_SUCCESS;
}
The most important change is that system headers must be surronded with < and >, instead of quotes. Also, it is better to know that the main() function always returns an int (to the operating system), and that this int is coded in two constants, EXIT_SUCCESS, and EXIT_FAILURE, in the header stdlib.h
Try something simpler:
printf("hello\tworld");
printf("hello\nworld");
and see what happens.
Your example with the BELL char, as others have pointed out, probably won't work on today's toasters^H^H^H^H^H^H^H^H computers; most terminals redirect the 'bell' character to either be discarded or to flash the terminal briefly.
And believe me, you want to keep it that way for the night-coding sessions :)
The above program which you have written I have tried it in the code blocks using GNU GCC Compiler..
It was working fine..
If you want to hear a beep sound you can try it another way it will only be useful in Windows!
#include<stdio.h>
#include<windows.h>
main()
{
Beep(600,600); /* you have to enter both the values whatever you want
}
As a matter of interest this appears to work in all builds that don't have a wWinMain or WinMain entry point. wprintf(L"\a") sounds fine for Unicode builds. (Win 7 here).
The PC speaker used to depend on "speaker.drv" but that little beauty has been taken away some time back and replaced with beep.sys which is now moved into the user mode system sounds agent.
Enabling and disabling the speaker from the command prompt is also discussed here.
#include<stdio.h>
int main()
{
int i = 263;
putchar(i); // or you can directly use putchar(263);
return 0;
}
This program produces a bell sound while you are on the output screen
the problem isnt about wheter your C program compiles its fully depend your terminal settings usually they make beeps using PC speakers that comes with laptop and PCs before UEFI exist
https://en.wikipedia.org/wiki/PC_speaker
i tested it using 2 laptops one of them were bought before UEFI even a thing and other bought after UEFI become common thing
i run echo -e '\a' on both test (both linux system with pcspkr module loaded) and sure the laptop before UEFI exist is beep other laptop just silent

Resources