-2

I am attempting to learn c programming.

I have written this small program:

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

int main(void) {
    // variable declarations
    long nc;
    char ch;

    // initialize variables
    nc = 0;

    while ((ch = getchar()) != EOF) {
        printf("%d\t%c\n", ch, ch);
        ++nc;
    }

    printf("Number of characters typed: %ld\n", nc);

    return EXIT_SUCCESS;
}

and I created a small text file like so:

echo "abcdef" > text.txt

When I run this program like so:

./countchar < text.txt

I get the following output:

97      a
98      b
99      c
100     d
101     e
102     f
10

Number of characters typed: 7

My question is what the 10 represents in this case (linefeed?) and why it appears as a seventh character when I have run this program using redirection.

phedor
  • 1
  • Did you open the text file in an editor? Did you read the manpage of `echo`? Did you do any effort to find the reason yourself? And ASCII `10` is not carriage return, but line feed. – too honest for this site May 28 '16 at 23:43
  • Try `echo -n "abcdef" > text.txt` if you are on Linux. – indiv May 28 '16 at 23:46
  • no i did not open it in an editor. I did exactly and only what i typed above. I did not read the manpage of echo as I am a complete, utter beginner working from a book. But i have read it now, thank you for the tip olaf, and have figured it out. – phedor May 28 '16 at 23:49

1 Answers1

2

When you do echo "abcdef", you get a line feed at the end. That's just how echo works by default. So, your text file contains 7 characters: abcdef\n.

Your c program works correctly and shows the number 10 (ASCII value of \n) and a literal line feed.

On most systems (but not all), you can do echo -n "abcdef" to avoid the new line. Alternatively (and more portably), use printf instead of echo if you care about the new line character.

Community
  • 1
  • 1
elixenide
  • 44,308
  • 16
  • 74
  • 100