Counting Tabs, New lines, etc. ~error~

M

Matt

Ok, sorry for posting so much, but I just have alot of questions. Ok,
so It says to make a program to count blanks, tabs, and newlines.

So I made one:

#include <stdio.h>

/* Count tabs, newlines and blanks; version 1 */
int main(void)
{
int c, nl, tb, cb;

nl = 0;
tb = 0;
cb = 0;
while ((c = getchar()) != EOF)
if (c == '\n')
++nl;
if (c == '\t')
++tb;
if (c == '_')
++cb;
printf("%d\n%d\n%d\n", nl, tb, cb);
return 0;
}

Now here's what I don't understand:

if (c == '\t')
++tb;

That(\t) be a tab so when I put a tab in it should make the count 1,
but it doesn't.

And:

if (c == '_')
++cb;

Should add a number to the blank count when you make a space, but it
doesn't. Also I wasn't sure about what the '?' was for a blank
space(eh, what a noob your thinking). Yes, I know: I'm a noob.

Ok well, could someone help me? Again: sorry for posting and asking so
much.
 
J

Jason

Matt wrote:
[ snip! ]
/* Count tabs, newlines and blanks; version 1 */
int main(void)
{
int c, nl, tb, cb;

nl = 0;
tb = 0;
cb = 0;
while ((c = getchar()) != EOF)
if (c == '\n')
++nl;
if (c == '\t')
++tb;
if (c == '_')
++cb;
printf("%d\n%d\n%d\n", nl, tb, cb);
return 0;
}

Hint: What is the significant difference between
the following bits of code?

/* SAMPLE #1 */
while ((c = getchar()) != EOF) {
/* some stuff */
/* some more stuff */
}
/* SAMPLE #2 */
while ((c = getchar()) != EOF)
/* some stuff */
/* some more stuff */
 
K

Keith Thompson

Matt said:
And:

if (c == '_')
++cb;

Should add a number to the blank count when you make a space, but it
doesn't. Also I wasn't sure about what the '?' was for a blank
space
[...]

No, that increments the blank count when it sees an underscore
character.

The right way to do this is (you're going to slap yourself in the
forehead when you see this):

if (c == ' ')
++cb;
 
O

Old Wolf

Matt said:
Ok, sorry for posting so much, but I just have alot of questions. Ok,
so It says to make a program to count blanks, tabs, and newlines.

if (c == '_')
++cb;

Should add a number to the blank count when you make a space, but it
doesn't. Also I wasn't sure about what the '?' was for a blank
space(eh, what a noob your thinking). Yes, I know: I'm a noob.

'_' is not a space. It's a different character. You can use
it in variable names, eg:

char this_is_a_char;

If you want to check for a space, use (naturally):

if (c == ' ')
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top