I have created an auto typing bot which simulate characters of string given by user.
My code is this:
printf("Enter speed (wpm) (1 to 11750):");
scanf("%d", &speed);
if(speed < 1 || speed > 11750)
{
printf("\nPlease provide CORRECT DATA\n");
return -1;
}
printf("Paste the String : \n");
gets(exaArray);
exaArrayLength = strlen(exaArray);
relation = (int)11750/speed;
printf("typing will start in 2 sec-\n");
Sleep(2000);
i=pos=0;
while(i<=exaArrayLength)
{
Sleep(relation);
if((exaArray[pos]>96) && (exaArray[pos]<123)) //small letters
{
keycode=0x41 + (exaArray[pos]%97);
smallLetter(keycode); //function for key simulation
}
.....
I am taking input using gets function. This program works fine when I paste text which does not contain Enter. So this program works fine with one paragraph.
But if the user provides more than one paragraph, then it simulates only the first paragraph.
Because gets terminates at '\n'. Which function could take multiple paragraph input and assign it to a string.
This is actually a very hard and complex problem, and not easy to solve in an automated way.
It would seem like reading in a loop would be a good solution, but then you come to the point when there is no more input and the reading function just blocks waiting for more input. The easiest way out of this is to have the user enter the "end of file" key combination (CTRL-D on POSIX systems like Linux or OSX, CTRL-Z on Windows), but the user must then be told to do that.
The problem stems from that your program simply have no idea how much data it is expected to read, and there is no function which is able to, basically, read the users mind when the user thinks "that's it, no more data".
Besides the above solution to have the user give an "end of file", you can use other sequences or special keys or even phrases of input to mark the end, but it all comes down to this: Read input in a loop until users says "no more input".
Well, there is no way for the computer to make a difference between the user pressing enter and the "pasted" string containing newlines. (Technically, pasting something into the console is like typing it.)
If you just don't want the problem to exit after one paragraph but continue, you can do it as commenter alk suggested (loop around the reading function) - then you would need Ctrl+C to exit the program and then there would technically still be one paragraph at a time written. Depends on what you further want to do with the program.
On the other hand, if you want a way for the user to input all text at once and only then process it, you would need to define something other than "newline" as "end of input" marker, for example something like ESC.
You would do this by using getchar instead of gets and manually concatenating each char which is entered this way to a string buffer, and if the character has the value 27 (escape key) for instance, you would end the input loop and start outputting.
Related
I am trying to learn the C language by following K&R2 reference book.
I wrote a program to count how many spaces, tabs and newlines are contained in a given input. (exercise 1-8 p.20)
How can I provide to this program input to test my code ?
#include<stdio.h>
main(){
int c,ne,nt,nf;
ne = 0;
nt = 0;
nf = 0;
while((c = getchar())!=EOF){
if (c == ' '){
ne++;
}if (c== '\t'){
nt++;
}if (c== '\n'){
nf++;
}
}
printf("Input contains %d spaces, %d tabs and %d newlines.",ne,nt,nf);
}
It depends on how you're running your program.
If you're running it from the command line, the program's standard input (which is where getchar reads from) is basically your keyboard, so you can just start typing.
If you're running under an IDE, it can create a new "terminal window" for your program to run in, and for you to type input in. At least for learning, such a terminal window ought to be the default, although unfortunately it seems that sometimes you have to take additional, nonobvious steps to set this up so that it will work.
When you're typing input on your keyboard, you also need a way of saying when you're done typing. You do this by typing a "control character". Under Unix, Linux, and MacOS it's control-D, and under Windows it's control-Z. (See also notes below.)
On a suitably powerful command line, you may also have various input redirection options available to you, such as reading input from a file by involving
./myprogram < filename
or taking some other program's output and "piping" it to your programs input by invoking something like
otherprogram | ./myprogram
A few more notes about control-D and control-Z:
On Unix, Linux, and MacOS, you either have to make sure you're typing the control-D at the beginning of a line (that is, you have to type Enter, then control-D), or if you're not at the beginning of a line, you have to hit control-D twice.
On Windows, you have to hit control-Z, then hit Enter.
(Computers can be so fussy sometimes! :-) )
Also, you should know that although typing control-D or control-Z indirectly results in an EOF value eventually squirting out as getchar's return value in your C program, you will not find that the macro EOF has a value of "control D" or "control Z". EOF is usually the value -1, and the process of turning a control character typed by you on the keyboard, into an EOF value returned by getchar in a C program, is actually a rather elaborate one.
[I've written several long writeups on that "rather elaborate process", but I can't seem to find any of them just now. If you're curious, check back in a couple days, and maybe I'll have found one, or written a new one.]
I am working on terminal based text editor and stuck at a point where I need to differentiate whether the input text from read() function is a clipboard paste text or a keyboard text input.
#include <unistd.h>
char read_key_input() {
char ch;
int read_count;
while ((read_count = read(STDIN_FILENO, &ch, 1)) != 1)
{
// Handle error if any
}
return ch;
}
...
Edit: Here's what I ended up doing.
void read_key_input(void (*callback)(int)) {
char* text = malloc(UINT8_MAX);
int read_count;
while ((read_count = read(STDIN_FILENO, text, UINT8_MAX)) == -1)
{
// Handle error if any
}
// Handle escape sequences if found and return early
...
if (read_count > 1) {
// It's probably a clipboard text. So change the editor mode to input and loop through all the characters one by one.
else {
// It's a user keyboard text input
}
// Revert back to the original editor mode if changed
}
I updated the code to retrieve more than one byte at a time (as suggested by #AnttiHaapala) and process each byte. Seems to be sufficient for my text editor's need for now. Will post back if I update.
Usually you can differentiate this by counting the number of characters you've received in rapid succession. So if you get the keypresses more rapidly than say 1000 characters per minute, then it is likely a clipboard paste... or nonsense.
Furthermore, if you've set the terminal to raw mode, then you can easily monitor individual keypresses. Also make read accept more than one byte at once - with read that is the maximum number of bytes to receive without blocking when available anyway.
One example of such an interactive terminal program would be IPython - here two lines typed separately:
In [1]: print("Hello")
Hello
In [2]: print("World")
World
And here pasted in one go:
In [3]: print("Hello")
...: print("World")
...:
Hello
World
Notice how the prompt is different, and the program runs only after there has been a separate Enter key hit after a small delay.
AFAIK, you cannot do what you want (reliably).
The clipboard is related (usually) to some display server, e.g. Xorg or Wayland server (Weston). And X11 might have distant clients (hence, a clipboard operation could be slow, if crossing some ocean).
Some Linux machines (perhaps the web server at Stackoverflow) do not run any display server.
You could code a GUI application, e.g. using GTK or Qt.
You could test if your standard input is a terminal with termios(3) functions or isatty(3) (i.e. with isatty(STDIN_FILENO) or isatty(STDOUT_FILENO) for standard output)
If your program is run inside a crontab(1) job, or a unix pipeline, the standard input won't be a terminal, and there might not even be any display server running.
You could take inspiration from the source code of GNU emacs, which does detect when a display server is available (probably using environ(7), e.g. getenv(3) of "DISPLAY"...)
On Linux you might open(2) /dev/tty (see tty(4)) to access your terminal. In some cases, it does not exist.
Hey #jiten not sure if you checked like
its key input detect and check wether it's input is one by one key
or its instant bulk input.
I'm writing a program that needs to ask the user a yes or no question at the end. Going based off the example .exe my teacher provided us, the line is supposed to print out "Would you like to print an Amortization Table(Y/N)?Y" and it looks for one keystroke from the user. The Y is printed out following the question like I typed, as it is supposed to represent the default choice so if the user presses [y], [shift + y], or [enter] it goes to the function that does the amortization table and if the user presses anything else it goes to the next line When it gets the input from the user it processes the keystroke instantly as it is pressed (it does not need [enter] to process the input) without letting the keystroke appear on the command prompt. I have tried all the functions I can think of to do this (getc, getchar, getche) but everything I have tried ends up printing the user's input. Does anyone know what function he used or what trick he is doing to keep the keystroke from appearing in the command prompt? Thanks for your help in advance, I am obviously new to programming.
For the Windows platform, use the _getch() function from <conio.h> to read a keypress without buffering or echo.
Read the function description on MSDN
I have this program in C that reads the input like this:
cod1 = getch ();
if (kbhit())
cod2 = getch ();
I can read every Ctrl+Char possible sequences, except for Ctrl+C, that closes the program - that is OK, and Ctrl+S, that simple is not catch. But I wanted to make Ctrl+S to be the save function in my program; how could I do that? Furthermore, is it possible to read Alt+Char characters? Because it reads it as a regular character, e.g., Alt+A is read with the same codes as A.
Your problem is that input probably gets eaten by terminal emulator.
For example Alt+<Whatever> is often reserved for menu shortcuts (e.g. Alt+F opens File menu). Matching characters are often hilighted once you hold Alt (F get's underscored in File).
Ctrl+S is reserved for Stops all output on screen (XOFF) (again your terminal emulator does that).
As for using Alt+<...> as shortcuts in your command line application. As far as I'm concerned holding Alt doesn't affect character received, it just sets flags which are hard to access in console. Even in GUI application (in Windows) it's quite tricky and you have to use function like GetAsyncState() to check whether alt was pressed.
I have a basic C program that needs to read input from stdin.
First, it reads from an input file by using
./Program <input
and then it loops through to read that until there's no more
while(scanf("%s",command)!=EOF){
printf("%s\n",command);
}
After that I need to read from the keyboard again, but it continues infinitely to spam read the last line from my input file, not letting me use my keyboard for input.
while(1){
scanf("%s",command);
if(!strcasecmp(command,"exit"))
exitProg();
else if(!strcasecmp(command,"help"))
helpMess();
else
printf("Command \"%s\" not recognized, use command \"help\" for a list.\n",command);
}
Read the documentation for scanf, specifically the part about the return value, excerpted below:
Return Value
On success, the function returns the number of items successfully read. This count can match the expected number of readings or fewer, even zero, if a matching failure happens.
In the case of an input failure before any data could be successfully read, EOF is returned.
The problem you're having is that once the file runs out of data, the program's standard-in does not revert back to the controlling terminal, it stays at the end of the empty file. Your scanf call is silently failing, leaving the contents of command unmodified. If you want to be able to read from both, you'd need to find another way of handling that.
It might be possible that your shell supports this functionality.