program that counts blanks, tabs, and newlines - c

I'm reading The C Programming Language. Here is a question which is saying Write a program to count blanks, tabs, and newlines. Now I can use \n for newlines and \t for tabs, but I am hearing first time about blanks! What it really mean by blanks? For the newlines and tabs, I have compiled following program:
#include <stdio.h>
/* program to count blanks, tabs, and newlines */
main (){
long blanks, tabs, newlines, input;
blanks = 0;
tabs = 0;
newlines = 0;
input = 0;
while ((input = getchar()) != EOF)
if (input == '\n')
++newlines;
else if (input == '\t')
++tabs;
printf("Total newlines: %ld\nTotal Tabs: %ld", newlines, tabs);
}

blanks = spaces (' ')
Though your code is working I strongly suggest adding { } for the body of the while loop.

A blank is simply a space, most of the time. You should probably look into the isblank() function to help with classification.

I'm sure they mean the space character ' '.
See here for the ASCII codes:
http://www.asciitable.com/
also 0x13 is carriage return, may want to look for that? Newlines are not actually that simple depending on how the file is formatted:
http://en.wikipedia.org/wiki/Newline
And like others have said, you may want to consider using functions from
http://www.cplusplus.com/reference/clibrary/cctype/

#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("Type and Press Enter. CTRL-Z for EOF:\n");
int c;
int b = 0;
int t = 0;
int nl = 0;
while((c = getchar())!=EOF){
putchar(c);
if(c=='\t')
++t;
if(c==' ')
++b;
if(c=='\n')
++nl
}
printf("\n%d and %d\n",b,t,nl);
return 0;
}
You've added a else if which is not required here since we need to know all the 3 values.

please find the code below this will get solution to your complete question.
#include <stdio.h>
/* Count blank, tabs, and new lines */
main ()
{
long c, b, t, l; /* c for characters, b for blanks, t for tabs, l for lines */
b = 0;
t = 0;
l = 0;
while ( ( c = getchar() ) != EOF )
{
if ( c == '\n')
++l;
if ( c == '\t')
++t;
if ( c == ' ')
++b;
}
printf ("\n No of blanks : %d \n", b);
printf ("\n No of tabs : %d \n", t);
printf ("\n No lines in input: %d \n", l);
}

I think blanks are new line followed by new line
#include<stdio.h>
int main()
{
int c,nl,nb,nt;
nl = 0;
nb = 0;
nt = 0;
int flag =1;
while((c = getchar()) != EOF){
if(c == '\n')
{
++nl;
if(flag)
++nb;
flag = 1;
}
else
flag = 0;
if(c == '\t')
++nt;
}
printf("lines : %d, tabs: %d, blanks: %d", nl, nt, nb);
return 0;
}

This answer -- benefited from other users' contributions -- uses only the material taught up to Exercise 1-8. When Ctrl+z is pressed (I used Windows DOS), the program jumps to printf statements, prints answers, then exits to DOS prompt.
#include <stdio.h>
/* Exercise 1-8. Write a program to count blanks, tabs, and newlines. */
int main()
{
int bl, tb, nl, c;
bl = 0;
tb = 0;
nl = 0;
while ((c = getchar()) != EOF) {
if (c == ' ')
++bl;
if (c == '\t');
++tb;
if (c == '\n');
++nl;
}
printf("Total blanks: %d\n", bl);
printf("Total tabs: %d\n", tb);
printf("Total newlines: %d\n", nl);
}
When you hit Enter key 5 times, press Spacebar 2 times, hit Tab key 4 times, then press Ctrl+z, you will get
Total blanks: 2
Total tabs: 4
Total newlines: 5
then DOS prompt.

the solution I think is :
#include <stdio.h>
main() {
int c, nl, nt, nb;
nl = 0;
nt = 0;
nb = 0;
while((c = getchar()) != EOF){
if (c == '\n')
++nl;
if (c == '\t')
++nt;
if (c == ' ')
++nb;
}
printf("Blanks: %d\nNewlines: %d\nTabs: %d\n", nl, nt, nb); }

Related

getchar() in C with while looping not printing afterwards

I don't understand why the printf() call after the while loop does not get executed?
int main(){
while((getchar()) != EOF){
characters ++;
if (getchar() == '\n'){
lines++;
}
}
printf("lines:%8d\n",lines);
printf("Chars:%8d",characters);
return 0;
}
I think you are trying to do that
#include<stdio.h>
int main()
{
int characters=0,lines=0;
char ch;
while((ch=getchar())!= EOF)
{
if (ch == '\n')
lines++;
else
{
characters++;
while((ch=getchar())!='\n'&&ch!=EOF); //is to remove \n after a character
}
}
printf("lines:%8d\n",lines);
printf("Chars:%8d",characters);
return 0;
}
Output:
a
s
d
f
^Z
lines: 1
Chars: 4
Process returned 0 (0x0) execution time : 8.654 s
Press any key to continue.
Note: ^Z(ctrl+z) is to send EOF to stdin (in windows)
You have to be careful of you're treatment in the while loop. Indeed, you are missing every caracter read in your while statement. You have to save this input, in order to use it afterwards.
The proper syntax would be while(( c = getchar()) != EOF)
You are probably looking for something like this:
#include <stdio.h>
int main()
{
int characters = 0;
int lines = 0;
int c;
while ((c = getchar()) != EOF) {
characters++;
if (c == '\n') {
lines++;
characters--; // ignore \n
}
}
printf("lines: %8d\n", lines);
printf("Chars: %8d", characters);
return 0;
}
while ((c = getchar()) != EOF) might look a bit confusing.
Basically it calls getchar, puts the returned valuee into c ands then checks if c equals EOF.

why does the first version print newline as 129 but the second works just fine?

when I run the first program, nl (newline) is set to 7ff, and prints out 129.
#include<stdio.h>
// countblanks-tabs-newlinesv1.c
void main()
{
long int c;
unsigned char nl, space, tab = 0 ;
while( ( c = getchar() ) != EOF)
{
if ( c == '\n')
{
nl++;
}
if ( c == ' ')
{
space++;
}
if ( c == '\t')
{
tab++;
}
}
printf("input has %d newlines, %d spaces and %d tabs\n", nl, space, tab);
}
But when I run the second program everything works fine...I think.
Second program
#include<stdio.h>
// countblanks-tabs-newlinesv2.c
void main()
{
long int c;
char space, tab ;
int nl;
nl = 0;
space = 0 ;
tab = 0;
while( ( c = getchar() ) != EOF)
{
if ( c == '\n')
{
nl++;
}
if ( c == ' ')
{
space++;
}
if ( c == '\t')
{
tab++;
}
}
printf("input has %d newlines, %d spaces and %d tabs\n", nl, space, tab);
}
btw this is exercise 1-8 in The C Programming Language Book
You didn't initialize nl and space to 0 in the first version. They have unpredictable initial values, so you get an unpredictable total.
When you write
unsigned char nl, space, tab = 0 ;
the = 0 initializer only applies to tab, not all the variables. You need to provide an initial value to each of them:
unsigned char nl = 0, space = 0, tab = 0 ;

Copying input to output without unnecessary Spaces in C

I'm trying to write a program in C that copies its input to its output while replacing each string of one or more Spaces with a single Space.
My code isn't doing that but is instead taking away every second character.
This is my code:
#include <stdio.h>
main()
{
int c;
int lastc;
lastc = 0;
while(getchar() != EOF){
c = getchar();
if(c == 32 && lastc == 32)
;
else
putchar(c);
lastc = c;
}
}
Your loop should look like:
while((c = getchar()) != EOF){
if(c == 32 && lastc == 32)
;
else
putchar(c);
lastc = c;
}
In your version you get a char with getchar while checking the condition for the while loop and then as a next step you again get a char with getchar. So the first one is not used in your code. Therefore it is taking away every second character.
Keep running in while loop until you get non-space character and print just one space after you get out.
int main()
{
int c;
bool space=false;
while ((c=getchar()) != EOF) {
while (isspace(c)) {
space = true;
c = getchar();
}
if (space) {
putchar(' ');
space = false;
}
putchar(c);
}
return 0;
}
I use fgets() function to getting string from input i.e stdin and store in the scroll string.
Then you must implement a way to analyze string to find spaces in it.
When you find first space, increase index if you face another space.
This is the code.
Code
#include <stdio.h>
int main(void){
char scroll[100];// = "kang c heng junga";
fgets(scroll, 100, stdin);
printf ("Full name: %s\n", scroll);
int flag = 0;
int i=0;
while (scroll[i] != '\0')
{
if (scroll[i] == ' ' )
flag=1;//first space find
printf("%c",scroll[i]);
if (flag==0){
i++;
}else {
while(scroll[i]==' ')
i++;
flag=0;
}
}
return 0;
}
Sample input: Salam be shoma doostane aziz
Program output: Salam be shoma doostane aziz
[Edit]
Use new string st to hold space eliminated string an print as output.
Also this code work for Persian string.
char scroll[100]={0};// = "kang c heng junga";
printf("Enter a string: ");
fgets(scroll, 100, stdin);
printf ("Original string: %s\n", scroll);
char st[100]={0};
int flag = 0;
int i=0;
int j=0;
while (scroll[i] != '\0')
{
if (scroll[i] == ' ' )
flag=1;//first space find
st[j]=scroll[i];
j++;
if (flag==0){
i++;
}else {
while(scroll[i]==' ')
i++;
flag=0;
}
}
printf("Eliminate Spaces: %s", st);

C code only prints after ^Z

I'm reading K&R's book on C and i got to this part where the output would be the number of newlines that you input.I wanted to make it so that it prints out each number corresponding to the amount of newlines typed as the lines are being read.This only outputs the value of nl after F6 or CTRL+Z has been pressed(EOF).Could someone explain to me why?
int main(){
int c, nl = 0;
while ((c = getchar()) != EOF)
if (c == '\n')
++nl;
printf("%d\n", nl);
}
You forgot some brackets. Here's what your code does currently:
int main(){
int c, nl = 0;
while ((c = getchar()) != EOF){
if (c == '\n'){
++nl;
}
}
printf("%d\n", nl);
}
Here's what you probably wanted to do based of indentation:
int main(){
int c, nl = 0;
while ((c = getchar()) != EOF){
if (c == '\n'){
++nl;
printf("%d\n", nl);
}
}
}
In C, whitespace is mostly ignored. If you want to run multiple statements together in a block, you need to surround that code with brackets {}
The while loop ends only when the character is an EOF character. EOF is a special character that represents the end of the file the program is reading. Since you are reading from the console, the console itself is the file you are reading from but it as no end. However in your system you can send an EOF character to the console by typing F6 or CTRL+Z
Instead if you want to print the number of lines while typing you should change your code like this:
int main(){
int c, nl = 0;
while ((c = getchar()) != EOF){
if (c == '\n'){
++nl;
printf("%d\n", nl);
}
}
}

counting the number of sentences in a paragraph in c

As part of my course, I have to learn C using Turbo C (unfortunately).
Our teacher asked us to make a piece of code that counts the number of characters, words and sentences in a paragraph (only using printf, getch() and a while loop.. he doesn't want us to use any other commands yet). Here is the code I wrote:
#include <stdio.h>
#include <conio.h>
void main(void)
{
clrscr();
int count = 0;
int words = 0;
int sentences = 0;
char ch;
while ((ch = getch()) != '\n')
{
printf("%c", ch);
while ((ch = getch()) != '.')
{
printf("%c", ch);
while ((ch = getch()) != ' ')
{
printf("%c", ch);
count++;
}
printf("%c", ch);
words++;
}
sentences++;
}
printf("The number of characters are %d", count);
printf("\nThe number of words are %d", words);
printf("\nThe number of sentences are %d", sentences);
getch();
}
It does work (counts the number of characters and words at least). However when I compile the code and check it out on the console window I can't get the program to stop running. It is supposed to end as soon as I input the enter key. Why is that?
Here you have the solution to your problem:
#include <stdio.h>
#include <conio.h>
void main(void)
{
clrscr();
int count = 0;
int words = 0;
int sentences = 0;
char ch;
ch = getch();
while (ch != '\n')
{
while (ch != '.' && ch != '\n')
{
while (ch != ' ' && ch != '\n' && ch != '.')
{
count++;
ch = getch();
printf("%c", ch);
}
words++;
while(ch == ' ') {
ch = getch();
printf("%c", ch);
}
}
sentences++;
while(ch == '.' && ch == ' ') {
ch = getch();
printf("%c", ch);
}
}
printf("The number of characters are %d", count);
printf("\nThe number of words are %d", words);
printf("\nThe number of sentences are %d", sentences);
getch();
}
The problem with your code is that the innermost while loop was consuming all the characters. Whenever you enter there and you type a dot or a newline it stays inside that loop because ch is different from a blank. However, when you exit from the innermost loop you risk to remain stuck at the second loop because ch will be a blank and so always different from '.' and '\n'. Since in my solution you only acquire a character in the innermost loop, in the other loops you need to "eat" the blank and the dot in order to go on with the other characters.
Checking these conditions in the two inner loops makes the code work.
Notice that I removed some of your prints.
Hope it helps.
Edit: I added the instructions to print what you type and a last check in the while loop after sentences++ to check the blank, otherwise it will count one word more.
int ch;
int flag;
while ((ch = getch()) != '\r'){
++count;
flag = 1;
while(flag && (ch == ' ' || ch == '.')){
++words;//no good E.g Contiguous space, Space at the beginning of the sentence
flag = 0;;
}
flag = 1;
while(flag && ch == '.'){
++sentences;
flag=0;
}
printf("%c", ch);
}
printf("\n");
I think the problem is because of your outer while loop's condition. It checks for a newline character '\n', as soon as it finds one the loop terminates. You can try to include your code in a while loop with the following condition
while((c=getchar())!=EOF)
this will stop taking input when the user presses Ctrl+z
Hope this helps..
You can implement with ease an if statement using while statement:
bool flag = true;
while(IF_COND && flag)
{
//DO SOMETHING
flag = false;
}
just plug it in a simple solution that uses if statements.
For example:
#include <stdio.h>
#include <conio.h>
void main(void)
{
int count = 0;
int words = 1;
int sentences = 1;
char ch;
bool if_flag;
while ((ch = getch()) != '\n')
{
count++;
if_flag = true;
while (ch==' ' && if_flag)
{
words++;
if_flag = false;
}
if_flag = true;
while (ch=='.' && if_flag)
{
sentences++;
if_flag = false;
}
}
printf("The number of characters are %d", count);
printf("\nThe number of words are %d", words);
printf("\nThe number of sentences are %d", sentences);
getch();
}
#include <stdio.h>
#include <ctype.h>
int main(void){
int sentence=0,characters =0,words =0,c=0,inside_word = 0,temp =0;
// while ((c = getchar()) != EOF)
while ((c = getchar()) != '\n') {
//a word is complete when we arrive at a space after we
// are inside a word or when we reach a full stop
while(c == '.'){
sentence++;
temp = c;
c = 0;
}
while (isalnum(c)) {
inside_word = 1;
characters++;
c =0;
}
while ((isspace(c) || temp == '.') && inside_word == 1){
words++;
inside_word = 0;
temp = 0;
c =0;
}
}
printf(" %d %d %d",characters,words,sentence);
return 0;
}
this should do it,
isalnum checks if the letter is alphanumeric, if its an alphabetical letter or a number, I dont expect random ascii characters in my sentences in this program.
isspace as the name says check for space
you need the ctype.h header for this. or you could add in
while(c == ' ') and whie((c>='a' && c<='z') || (c >= 'A' && c<='Z')
if you don't want to use isalpace and isalnum, your choice, but it will be less elegant :)
The trouble with your code is that you consume the characters in each of your loops.
a '\n' will be consumed either by the loop that scans for words of for sentences, so the outer loop will never see it.
Here is a possible solution to your problem:
int sentences = 0;
int words = 0;
int characters = 0;
int in_word = 0; // state of our parser
int ch;
do
{
int end_word = 1; // consider a word wil end by default
ch = getch();
characters++; // count characters
switch (ch)
{
case '.':
sentences++; // any dot is considered end of a sentence and a word
break;
case ' ': // a space is the end of a word
break;
default:
in_word = 1; // any non-space non-dot char is considered part of a word
end_word = 0; // cancel word ending
}
// handle word termination
if (in_word and end_word)
{
in_word = 0;
words++;
}
} while (ch != '\n');
A general approach to these parsing problems is to write a finite-state machine that will read one character at a time and react to all the possible transitions this character can trigger.
In this example, the machine has to remember if it is currently parsing a word, so that one new word is counted only the first time a terminating space or dot is encountered.
This piece of code uses a switch for concision. You can replace it with an if...else if sequence to please your teacher :).
If your teacher forced you to use only while loops, then your teacher has done a stupid thing. The equivalent code without other conditional expressions will be heavier, less understandable and redundant.
Since some people seem to think it's important, here is one possible solution:
int sentences = 0;
int words = 0;
int characters = 0;
int in_word = 0; // state of our parser
int ch;
// read initial character
ch = getch();
// do it with only while loops
while (ch != '\n')
{
// count characters
characters++;
// count words
while (in_word)
{
in_word = 0;
words++;
}
// skip spaces
while (ch == ' ')
{
ch = -1;
}
// detect sentences
while (ch == '.')
{
sentences++;
ch = -1;
}
// detect words
while ((ch != '\n')
{
word_detected = 1;
ch = -1;
}
// read next character
ch = getch();
}
Basically you can replace if (c== xxx) ... with while (c== xxx) { c = -1; ... }, which is an artifical, contrieved way of programming.
An exercise should not promote stupid ways of doing things, IMHO.
That's why I suspect you misunderstood what the teacher asked.
Obviously if you can use while loops you can also use if statements.
Trying to do this exercise with only while loops is futile and results in something that as little or nothing to do with real parser code.
All these solutions are incorrect. The only way you can solve this is by creating an AI program that uses Natural Language Processing which is not very easy to do.
Input:
"This is a paragraph about the Turing machine. Dr. Allan Turing invented the Turing Machine. It solved a problem that has a .1% change of being solved."
Checkout OpenNLP
https://sourceforge.net/projects/opennlp/
http://opennlp.apache.org/

Resources