how to make a 'backspace' program in C? - c

I am creating some library function for print and scan using assembly language and c.
Now when am entering datas it is getting print,but the problem is when i press the backspace button the cursor is moving backwards(but not deleting anything)..I want the backspace button to work properly(ie,to delete the previous character)
so is there any program for that.Please help me.

The simple, albeit somewhat hackish, way is to just write backspace characters (\b) to the console.
For example:
#include <stdio.h>
int main()
{
printf("Testing");
fflush(stdout);
printf("\b\b\b");
fflush(stdout);
return 0;
}
But this type of thing should really be handled by your terminal driver. You don't mention what operating system you're targeting in the question.

Output a backspace, space, and backspace:
int c = getchar();
if (c == '\b')
{
printf("\b \b");
fflush(stdout);
}
If the user's press of a backspace was already echoed by the terminal driver then just do this:
int c = getchar();
if (c == '\b')
{
printf(" \b");
fflush(stdout);
}

if u r doing so then would like to tell you one thing abt consoles
There are 2 types of consoles , one which can recognize control char. called
Active console(Canonical mode) and one which not called row console .
Obviously if u r using unix's terminal then u will be given default as Active mode console
but u can set it to row mode by executing some commands.

Related

Why I can't reach stdin at startup on Raspberry-Pi Jessie Lite?

I have this code. what I want to do is to wait for user to press 'q' to end the program.
.
...starting few threads, which use fflush(stdout) (just saying...)
.
char n = 0;
while (n != 'q') {
n = getchar(); //tried to use scanf() here as well
printf("%c", n);
}
...killing all threads...
return 0;
When I run this in a normal Linux enviroment it works fine.
The problem starts when I run this program at startup on my raspberry-pi with debian jessie lite distribution (I added the path to the program to /etc/rc.local) - it ends in an infinite loop, scanf is still returning -1 and getchar() some weird character and the program won't end, when I press q. Ctrl+C doesn't work either so there is no way, how to end the program.
Any suggestions? (at least how to kill the program...?)
Edit: To let you know what the program does.
Raspberry-pi with this program is attached to some serial ports and converts and transfers some GPS data. It should work "out of the box" without any keyboard or mouse or monitor. = Just plug the device to some cables and do nothing more. In some cases someone would like to see log files on the raspberry, so he needs to stop the program, obviously.
Edit2: when I did the same with some normal Raspbian, it worked fine too.
Update:
I tried to debug it - shrinked the code to this only
int main(void){
char n=0;
int x;
while (n != 'q'){
clearerr(stdin);
x=scanf("%c",&n);
printf("%c %d\n",n,x);
}
return 0;
}
added service start udev to rc.local and tried command update.rc.d udev enable
output on raspberry-pi when launched at startup is still
-1
-1
-1
.
.
so there definitely have to be something wrong with stdin.
After startup and on other systems, the output is obviously q 1 (when I press 'q' (and enter) ...)
when I tried to read from /dev/tty, fopen() returned NULL
Really need a help with this
The idiomatic way to write this loop is:
int c;
while ((c = getchar()) != EOF && c != 'q'){
putchar(c);
}
Your implementation cannot detect end of file and will loop forever, printing funny characters such as ÿ.
Just a wild guess that stdin maybe redirected to something else and you need to read from keyboard directly. try the following code:
FILE *tty = fopen("/dev/tty", "r");
if (!tty) {
exit(1);
}
int n=0;
while (n != 'q'){
n=fgetc(tty); //tried to use scanf() here as well
printf("%c",(char)n);
}

How to display asterisks for password input only after two consecutive colons?

I want to read input from user. After the user typed the sequence ::, the rest of the input should be asterisks.
For example: let's say user typed: Alex::vn800. On the screen, the output should be: Alex::*****.
I have a function that reads input from user and display * on screen, but I didn't managed to use it in a middle of reading line.
I tried to manipulate functions getchar() and scanf() to stop reading line after detecting a sequence of ::, and then call the function but nothing worked.
What can I do?
Update: Hey! thanks for the answers.
I fainlly solved the problem by using the library conio.h - like in any other simple get-password code, just that I saprated it for cases according to what I want the screen will show and not just '*' for any case.
If it's not strictly necessary to have both username and password in the same line, I would suggest simply getting the username first and then using the getpass() function, like here.
I've tried ataman's method, but it didn't work on OSX 10.9.
Here's a modified version, following goldPseudo's approach:
#include <stdio.h>
#include <stdlib.h>
int main() {
int readChar;
int status = 0;
int semicolonCount = 0;
system ("/bin/stty raw"); // disable buffering and other stuff
while ((readChar = getchar()) && (readChar != 13 /* ENTER keycode */))
{
if (status == 0)
{
printf("%c", readChar);
if (readChar == ':')
{
semicolonCount++;
} else {
semicolonCount = 0;
}
if (semicolonCount == 2)
{
status = 1;
}
} else {
printf("*");
}
}
printf("\r\n"); // print new line
system ("/bin/stty cooked"); // reenable buffering, might not be the original mode the terminal was in
return 0;
}
The problem with this approach is that, since you are in "raw mode", special characters, like BACKSPACE, ENTER, Ctrl+D and even Ctrl+C, are not processed.
You would have to implement the behaviour for those characters yourself.

Generate a "readable" backspace in command prompt

How can I generate a "readable" backspace in command prompt?
I have a tiny C app and I'm trying to read a backspace from input with getchar() method.
Is there any key combination to trigger this (and still being able to capture it)? (Similar to Ctrl-Z to trigger an EOF)
Backspace is special! Normally you will need to use some raw/unbuffered keyboard I/O mode to capture it.
On Windows you may want to try using getch instead of getchar. See also: What is the difference between getch() and getchar()?
You can use curses function getch() to read backspace.
Chech the following link -
how to check for the "backspace" character in C
In the above link in answer ascii value of backspace is used to read it .
Ascii code of backspace button is 127, so every function returns an integer from terminal input will probably return 127 in case of backspace. Be careful because it is the same code for delete button.
Linux
See this answer first and implement your own getch() then follow Windows code example (obviously without conio.h lib).
Windows
Just add #include<conio.h>in the beginning of your source file.
This is my SSCCE, just need to write something like this
int main(void) {
int c;
while (1) {
c = getch();
if (c == 127) {
printf("you hit backspace \n");
} else {
printf("you hit the other key\n");
}
}
return 0;
}

Capturing a user's "enter" keystroke in C

I'm starting to learn C now and i'm trying to figure out how I would go about capturing when the user hits "enter." I'm looking particularly at the scanf and getc functions but I'm not quite sure how to go about it. When the user hits enter I want to perform some operations while waiting/watching for him to hit enter again... Is "enter" a new line character coming in from the console? Any advice would be much appreciated!
You can check the ascii value using fgetc().
while(condition) {
int c = fgetc(stdin);
if (c==10) {//Enter key is pressed
//your action
}
}
If you just need the input when user presses enter as input you can use scanf or getchar. Here is an example from cplusplus.com
/* getchar example : typewriter */
#include <stdio.h>
int main ()
{
char c;
puts ("Enter text. Include a dot ('.') in a sentence to exit:");
do {
c=getchar();
putchar (c);
} while (c != '.');
return 0;
}
This code prints what you entered to stdin (terminal window).
But if you do not want the input ( i know it's really unnecessary and complicated for a new learner) you should use an event handler.
printf("Hit RETURN to exit"\n");
fflush(stdout);
(void)getchar();
Ref: comp.lang.c FAQ list · Question 19.4b
The C language is platform-independent and does not come with any keyboard interaction on its own. As you are writing a console program, it is the console that processes the keyboard input, then passes it to your program as a standard input. The console input/output is usually buffered, so you are not able to react to a single keypress, as the console only sends the input to the program after each line.
However! If you do not demand your console application to be platform-independent, there is a non-standard library <conio.h> in some Windows compilers that has a function called getche();, which does exactly what you want - wait for a single keypress from the console, returning the char that was pressed.

count the number of lines, words, and characters within an input

Right now I am going through a book on C and have come across an example in the book which I cannot get to work.
#include <stdio.h>
#define IN 1
#define OUT 0
main()
{
int c, nl, nw, nc, state;
state = OUT;
nl = nw = nc = 0;
while ((c = getchar()) != EOF) {
++nc;
if (c == '\n')
++nl;
if (c == ' ' || c == '\n' || c == '\t')
state = OUT;
else if (state == OUT) {
state = IN;
++nw;
}
}
printf("%d %d %d\n", nl, nw, nc);
}
It's supposed to count the number of lines, words, and characters within an input. However, when I run it in the terminal it appears to do nothing. Am I missing something or is there a problem with this code?
The program only terminates when the input ends (getchar returns EOF). When running on terminal, this normally never happens and because of this it seems that the program is stuck. You need to close the input manually by pressing Ctrl+D (possibly twice) on Linux or pressing F6 and Enter at the beginning of the line on Windows (different systems may use different means for this).
It's waiting for input on stdin. Either redirect a file into it (myprog < test.txt) or type out the data and hit Ctrl-D (*nix) or Ctrl-Z (Windows).
When you run it, you need to type in your text, press return, then type Ctrl-d and return (nothing else on the line) to signify end-of-file. Seems to work fine with my simple test.
What it is doing is entering a loop for input. If you enter a character or newline, nothing happens on the screen. You need to interrupt the process (on my Mac this is CTRL+D) which serves as EOF. Then, you will get the result.
getchar() returns the input from the standard input. Start typing the text for which you want to have the word count and line count. Your input terminates when EOF is reached, which you do by hitting CTRL D.
CTRL D in this case acts as an End Of Transmission character.
cheers
I usually handle this kind of input like this (for Linux):
1. make a file (for example, named "input.txt"), type your input and save
2. use a pipe to send the text to your application (here assume your application named "a.out" and in the current directory):
cat input.txt | ./a.out
you'll see the program running correctly.

Resources