Home > Net >  How do I check if my code responds correctly to a backspace character?
How do I check if my code responds correctly to a backspace character?

Time:07-30

I'm learning c from K&R's book, and I wanted to work on this task:

enter image description here

My code, which is here:

#include <stdio.h>

int main()
{
    int c;

    while ((c = getchar()) != EOF) {
        if (c == '\t') {
            putchar('\\');
            putchar('t');
        }
        else if (c == '\b') {
            putchar('\\');
            putchar('b');
        }
        else if (c == '\\') {
            putchar('\\');
            putchar('\\');
        }
        else
            putchar(c);
    }
}

works just fine with slashes and tabs, but I don't know how to check if my code works with a real backspace character in text (If it's even possible?).

I used this input:

there will be now an tab:   .
in additon, here are three slashes: \,\,\.

and checked the output in this site, and it worked just fine, I got this output:

there will be now an tab: \t.
in additon, here are three slashes: \\,\\,\\.

CodePudding user response:

I'm old enough to remember when character streams sent to line printers (and dot matrix printers) would use 'backspace' to overstrike to show as bold.

You've done everything correctly, but want to prove your if/else works for backspace.

Temporarily replace the while loop with a "custom string"... This should do the trick...

// while ((c = getchar()) != EOF) {
for( char *cp = "Test\b\t\\ Done\n"; (c = *cp ) != '\0'; cp   ) {

CodePudding user response:

You can use a hex editor to put a backspace character into a text file. The character code of the backspace character is 8 in ASCII. Most IDEs have a built-in hex editor (see the linked instructions for Visual Studio and Visual Studio Code).

You can also write a short program which creates a small text file for you, which contains a backspace character:

#include <stdio.h>
#include <stdlib.h>

int main( void )
{
    FILE *fp;

    fp = fopen( "test.txt", "wx" );
    if ( fp == NULL )
    {
        fprintf( stderr, "Error opening file!\n" );
        exit( EXIT_FAILURE );
    }

    fputs(
        "This is a line without a backspace character.\n"
        "This is a line with a backspace charax\bcter.\n",
        fp
    );

    fclose( fp );
}

Note that due to the "wx" mode used when opening the file, it will fail to open the file if the file already exists. If you do not want this, then you can change the mode to "w", in which case it will overwrite the file if it already exists.

Once you have a text file with a backspace character, you can pipe it to the standard input of your program, for example by calling your program like this:

myprogramname <test.txt

When running your program from inside an IDE, it should also be possible to configure it in such a way that standard input is piped from a file.

  •  Tags:  
  • c
  • Related