2

I'm trying to write a short program that puts each word on a new line. The new line can be confirmed by tabulator, space or enter. The end of program is putting "#" in console. I have the problem that when I put "enter" to the console it writes next characters in the same line.

The second idea is to make all of this in a table, so I can put formatted text all together in the end. I can't figure this out either.

#include<stdio.h>
#include <conio.h>
#define STOP '#'
int main()

{

    char ch;
    while ((ch = (_getch())) != STOP) {
        switch (ch) {
        case '\n':
            printf("\n");
            break;
        case '\t':
            printf("\n");
            break;
        case ' ':
            printf("\n");
            break;
        default:
            putchar(ch);
        }

    }

    printf("\nEND");
    _getch();


    return 0;
}
shurrok
  • 795
  • 2
  • 13
  • 43
  • 1
    Did you check what is returned by `_getch()` when you provide "enter"? – Martin Nov 02 '16 at 12:08
  • 2
    In Windows, you issue "\r\n" for a new line. – 001 Nov 02 '16 at 12:11
  • @JohnnyMopp The C standard requires `printf("\n")` to DTRT, regardless of whether the OS line terminator is a single character. (Specifically, both input and output on FILE objects open in text mode are required to convert between `\n` and whatever the OS's line terminator is.) `_getch` is not part of the C standard so it isn't subject to this rule. – zwol Nov 02 '16 at 12:36

2 Answers2

5

Because hitting "enter" issues a carriage return char (\r), not a linefeed one.

I noticed it when the cursor jumped back at the start of the line when I pressed "enter".

Fix your code like this (factorize the case statements too):

#include<stdio.h>
#include <conio.h>
#define STOP '#'
int main()

{

    char ch;
    while ((ch = (_getch())) != STOP) {
        switch (ch) {
         case ' ':
         case '\t':
         case '\r':   // what was missing
            printf("\n");
            break;
        default:
            putchar(ch);
        }

    }

    printf("\nEND");
    _getch();


    return 0;
}
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
4

You probably get a carriage return ('\r') which is what Return typically generates.

So you need to check for that, too. Your code can be simplified:

int main(void)
{
  while((ch = _getch()) != STOP)
  {
    if(ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t')
      ch = '\n';
    putchar(ch);
  }
}

Since we're always printing exactly one character per iteration, no need to use multiple printing functions. Also, using printf() to print a single constant character is overkill.

unwind
  • 391,730
  • 64
  • 469
  • 606