Search code examples
cuser-input

How to input of a string which contain '\n' in it


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.


Solution

  • 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.