Counting Number of words and Characters in a Sentence using C - c

I tried the below program .
INPUT-: i want help
Desired OUTPUT-:Words=3 Characters=9
But the actual output deviates from the desired.
Can someone tell what is my mistake .
include
void main()
{
int countch=0;
int countwd=1;
printf("Enter your sentence in lowercase: ");
char ch='a';
while(ch!='\r')
{
ch=getche();
if(ch==' ')
countwd++;
else
countch++;
}
printf("\n Words = ",countwd);
printf("Characters = ",countch-1);
getch();
}

Be advised: getchar() returns int, not char. This is one of the most common pitfalls for beginning C programmers, it seems.
Also, you should check for the special value EOF and stop the program if it occurs; this is the typical and "clean" way of doing programs that read input and will make the program automatically handle both interactive input (from a terminal) and input from a file.

There are few observations which you might find of some use:
1. You are using getch & getche which are both non-standard functions. Make use of getchar instead. In this case as already pointed in unwind's response you need to use int for the return type.
2. Please change the return type of main from void to int.
3. You are not specifying the formats in printf. Please add %d specifier to print integers.
I have not used codepad but ideone allows you to add inputs to your programs. Here is a reference based on your sample on ideone.
Hope this helps!

#include<stdio.h>
#include<stdbool.h>
int main(void)
{
char c = '\0';
int nw = 0,nc = 0,nl = 0;
bool flag = true;
bool last = false,cur = false;
while(flag && (c = getchar())) {
if(c != EOF)
++nc;
else
flag = false;
if(c == '\n') nl++;
cur = (c == EOF || c == ' ' || c == '\t' || c == '\n')?false:true;
if(last && !cur )
++nw;
last = cur;
}
printf("\nNo of chars : %d",nc);
printf("\nNo of lines : %d",nl);
printf("\nNo of words : %d",nw);
return 0;
}

Related

print each letter after '.' for example if I enter a..bcde..fg..h the program will print bfh

I'm new to C, I have been asked to make a program in C asking to print each letter after a '.' after a user has entered an input.
For example if the user enters a..bcd..e.f..gh the output should be befg
which is the exact example I have been given in class.
I assume this would need to use pointers but I am unsure how to deal with this question, here is what I have tried to do so far. I know it is not correct, please help me understand how to use pointers to deal with this question.
#include <stdio.h>
int main() {
char *c, count =0;
printf("enter some characters");
scanf("%s", &c);
while( c != EOF ) {
if (c != '.') {
count ++;
}
else; {
printf("%s", c);
}
}
}
The program can look the following way
#include <stdio.h>
#define N 100
int main( void )
{
char s[N];
const char DOT = '.';
printf( "Enter some characters: " );
fgets( s, N, stdin );
for ( char *p = s; *p; ++p )
{
if ( p[0] == DOT && p[1] != DOT ) putchar( p[1] );
}
putchar( '\n' );
}
Its output might look like
Enter some characters: a..bcd..e.f..gh
befg
Take into account that here any symbol after a dot (except the dot itself) is printed. You can add a check that there is a letter after a dot.
You don't really need pointers for this, or even an array. Basically it's a simple state engine: read each character, if '.' is encountered, set a flag so the next character is printed.
#include <stdio.h>
int main() {
int c, flag = 0;
while ((c = getchar()) != EOF) {
if (c == '.')
flag = 1;
else if (flag) {
putchar(c);
flag = 0;
}
}
return 0;
}
There are some errors in your code:
- char* c means a pointer to one or more characters.
But where does it point to?
- scanf reads a string up to an "white space". White space characters are the space itself, a newline, a tab character or an EOF. scanf expects a format string and a pointer to a place in memory where it places what it reads. In your case c points to an undefined place and will overwrite whatever there is in memory.
- why do you place a ";" after the else? The else clause will end with the ";". So your program will do the print every time.
It helps you a lot if you format your code in a more readable way and give the variable names that give hint what they are used for.
Another very important thing is to initialize every variable that you declare. Errors with uninitialized variables are sometimes very hard to find.
I would do it this way:
#include <stdio.h>
int main(int argc, char* argv[])
{
// I read every single character. The getchar function returns an int!
int c = 0;
// This marks the program state whether we must print the next character or not
bool printNext = false;
printf("enter some characters");
// We read characters until the buffer is empty (EOF is an integer -1)
do
{
// Read a single character
c = getchar();
if ( c == '.')
{
// After a point we change our state flag, so we know we have to print the next character
printNext = true;
}
else if( c != EOF )
{
// When the character is neither a point nor the EOF we check the state
if( printNext )
{
// print the character
printf( "%c", c );
// reset the state flag
printNext = false;
}
}
// read until the EOF occurs.
}
while( c != EOF );
}
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
char letter;
char *c;
c = malloc(256);
printf("enter the string : ");
scanf("%s", c);
while( (letter=*(c)) != '\0' )
{
if (letter == '.')
{
c++;
letter=*c;
if(letter!='.')
printf("%c",letter);
else
{
while(letter=='.')
{
c++;
letter=*c;
}
printf("%c",letter);
}
}
c++;
}
printf("\n");
}

printing a word per line

I need to write a program that prints its input one word per line. Here's what I got so far:
#include <stdio.h>
main(){
int c;
while ((c = getchar()) != EOF){
if (c != ' ' || c!='\n' || c!='\t')
printf("%c", c);
else
printf("\n");
}
}
The logic is pretty simple. I check to see if the input is not a newline, tab or space, and in that case it prints it, otherwise prints a newline.
When I run it, I get results like this:
input--> This is
output--> This is
It prints the whole thing. What goes wrong here?
if (c != ' ' || c!='\n' || c!='\t')
This will never be false.
Perhaps you meant:
if (c != ' ' && c!='\n' && c!='\t')
instead of using printf try putchar, also as per above comments, you should use && instead of ||.
here is my code-
#include<stdio.h>
main()
{
int c, nw; /* nw for word & c for character*/
while ( ( c = getchar() ) != EOF ){
if ( c != ' ' && c != '\n' && c != '\t')
nw = c;
else {
nw = '\n';
}
putchar (nw);
}
}
this code will give you the desired output
you can use if you want the strtok function in string.h library which can cut the input into many words by providing a delimiter.
Here is a perfect code commented which can fit to your needs
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
char line[1000]=""; // the line that you will enter in the input
printf("Input the line:\n>>");
scanf("%[^\n]",line); // read the line till the you hit enter button
char *p=strtok(line," !#$%&'()*+,-./'"); // cut the line into words
// delimiter here are punctuation characters (blank)!#$%&'()*+,-./'
printf("\nThese are the words written in the line :\n");
printf("----------------------------------------\n");
while (p!=NULL) // a loop to extract the words one by one
{
printf("%s\n",p); // print each word
p=strtok(NULL," !#$%&'()*+,-./'"); // repeat till p is null
}
return 0;
}
If we execute the code above we will get
Input the line:
>>hello every body how are you !
These are the words written in the line :
----------------------------------------
hello
every
body
how
are
you
suggest the code implement a state machine,
where there are two states, in-a-word and not-in-a-word.
Also, there are numerous other characters that could be read
(I.E. ',' '.' '?' etc) that need to be check for.
the general logic:
state = not-in-a-word
output '\n'
get first char
loop until eof
if char is in range a...z or in range A...Z
then
output char
state = in-a-word
else if state == in-a-word
then
output '\n'
state = not-in-a-word
else
do nothing
end if
get next char
end loop
output '\n'
I think the simple solution would be like
#include <stdio.h>
int main(void) {
// your code goes here
int c;
while((c=getchar())!=EOF)
{
if(c==' ' || c=='\t' || c=='\b')
{
printf("\n");
while(c==' ' || c=='\t' || c=='\b')
c=getchar();
}
if(c!=EOF)
putchar(c);
}
return 0;
}

How to get input of string with space and put it in variables separate?

I got stuck with this, i can't figure out when set input. Example -> "LEMON TREE", (there i set that(input) to read it double time function getline), it give me wrong output like "LEMON TRE E" down i explain this more, question is how i can change code for getline(mine modified function) and get output separate, here is my function getline, and here is visual what i want.
I use function from k&r-ansii book(little modified):
int getline(char *line, int len)
{
int i,c;
for ( i =0;i<len-1 && (c = getchar()) != EOF && c!='\n';i++)
*line++ = c;
if ( c == '\n')
{
i++;
*line++ = '\n';
*line = '\0';
}
return i;
}
And this is visual what i want:
char line_1[10];
char line_2[10];
getline(line_1, 10);
getline(line_2, 10);
printf("line_1: %s ", line_1);
printf("line_2: %s", line_2);
INPUT: LEMON TREE // This is input in one line like u see.
OUTPUT: line_1: LEMON TRE line_2: E
What i need to change in my code?
When i write getline in header it say that it got previous declared, now when i use ubuntu, but before when was on windows i declared that and mix also with lib stdio.h and it have worked all right.
UPDATE: I want to change my function, that it can work with more words than two(to make it universal) .
You need to check for whitespaces (eg. space) as well to determine where the word ends
for ( i =0;i<len-1 && (c = getchar()) != EOF && c!='\n' && c!=' ';i++) {
*line++ = c;
}
/*EDIT: (thanks to BLUEPIXY's comment for reminding me) Alyways use string (or other data type) large enough to contain possible input/value assigned to it.
*/
as for universality of the function you can either call getline in a cycle and use its return value to determine whether the last word was already read or use multidimensional array
while (getline(line_1, 10)!= -1) {
printf("line_1: %s ", line_1);
}
Don't forget to edit return value of the function (I'm used to assign values that are are impossible to be returned any other way (usually negative values mean error while counting something):
if ((c == EOF) ||(c == '\n')) {
i = -1;
}
also
if ( c == '\n')
{
i++;
*line++ = '\n';
*line = '\0';
}
should be simply replaced with
*line = '\0'; //every string needs to be finalized
as for 2nd question, according to http://www.cplusplus.com/reference/cstdio/ stdio.h does not contain getline function

K&R answer 1-12 (using functions to reduce the number of lines of code)

I have written the following program to answer Kernighan and Ritchies ch1 problem 12.
The issue is that I have never really understood how to properly use functions and would like to know why the one I wrote into this program, getcharc(), does not work?
What are good resources that explain correct function usage. Where? and How?
I know the optimal solution to this problem from Richard Heathfield's site (which uses || or, rather than nested while statements, which I have used), however I would like to know how to make my program work properly:
#include <stdio.h>
int getcharc ();
// Exercise 1-12
// Copy input to output, one word per line
// words deleniated by tab, backspace, \ and space
int main()
{
int c;
while ((c = getchar()) != EOF) {
while ( c == '\t') {
getcharc(c);
}
while ( c == '\b') {
getcharc(c);
}
while ( c == '\\') {
getcharc(c);
}
while ( c == ' ') {
getcharc(c);
}
putchar(c);
}
}
int getcharc ()
{
int c;
c = getchar();
printf("\n");
return 0;
}
The original program (and I know it has bugs), without the function was:
#include <stdio.h>
// Exercise 1-12
// Copy input to output, one word per line
// words deleniated by tab, backspace, \ and space
int main()
{
int c;
while ((c = getchar()) != EOF) {
while ( c == '\t') {
c = getchar();
printf("\n");
}
while ( c == '\b') {
c = getchar();
printf("\n");
}
while ( c == '\\') {
c = getchar();
printf("\n");
}
while ( c == ' ') {
c = getchar();
printf("\n");
}
putchar(c);
}
}
So all I am trying to do with the function is to stop
c = getchar();
printf("\n");
being repeated every time.
What, exactly, is this getcharc() function supposed to do? What it does, is read a character from input, print a newline, and return zero. The character just read from input is discarded, because you didn't do anything with it. When it's called, the return value is ignored as well. In each of the places where it is called, you're calling it in an infinite loop, because there's no provision made for changing the loop control variable.
Perhaps you were intending something like c = getcharc(), but that wouldn't really help because you aren't returning c from the function, anyway. (Well, it would help with the "infinite loop" part, anyway.)
What's the point of this function anyway? If you just use getchar() correctly in its place, it looks like you'd have your solution, barring a few other bugs.
One of the possible solution is, change prototype for your function to int getcharc (int c, int flag).
Now your code after some modification;
#include <stdio.h>
int getcharc (int c, int flag);
// Exercise 1-12
// Copy input to output, one word per line
// words deleniated by tab, backspace, \ and space
int main()
{
int c;
int flag = 0; //to keep track of repeated newline chars.
while ((c = getchar()) != '\n') {
flag = getcharc(c, flag); // call getcharc() for each char in the input string. Testing for newline and printing of chars be done in the getcharc() function
}
return 0;
}
int getcharc (int c, int flag)
{
if( (c == ' ' || c == '\t' || c == '\b' || c== '\\') && flag == 0)
{
printf("\n");
flag = 1;
}
else
{
if(c != ' ' && c != '\t' && c != '\b' && c!= '\\')
{
putchar(c);
flag = 0;
}
}
return flag;
}
EDIT:
but I wanted to keep the nested while statements rather than using || or
Your nested while loop is executing only once for each character as grtchar() reads one character at one time. No need of nested loops here! You can check it by replacing while to if and your code will give the same output for a given string. See the output here.
know the optimal solution to this problem from Richard Heathfield's site (which uses || or, rather than nested while statements, which I have used), however I would like to know how to make my program work properly:
You make your program work to some extent (with your bugs) by adding an if condition and a break statement as;
#include <stdio.h>
int getcharc (int c);
int main()
{
int c;
while ((c = getchar()) != '\n') {
while ( c == '\t') {
c = getcharc(c);
if(c != '\t')
break;
}
....
....
while ( c == ' ') {
c = getcharc(c);
if(c != ' ')
break;
}
putchar(c);
}
return 0;
}
int getcharc (int c)
{
c = getchar();
printf("\n");
return c;
}
// compiled by my brain muhahaha
#include <stdio.h>
int getcharc(); // we prototype getcharc without an argument
int main()
{
int c; // we declare c
// read character from stdio, if end of file quit, store read character in c
while ((c = getchar()) != EOF) {
// if c is tab \t call function getcharc() until forever since c never changes
while ( c == '\t') {
getcharc(c); // we call function getcharc with an argument
// however getcharc doesn't take an argument according to the prototype
}
// if c is \b call function getcharc() until forever since c never changes
while ( c == '\b') {
getcharc(c);
}
// if c is \\ call function getcharc() until forever since c never changes
while ( c == '\\') {
getcharc(c);
}
// if c is ' ' call function getcharc() until forever since c never changes
while ( c == ' ') {
getcharc(c);
}
// since we never will get here but if we happened to get here by some
// strange influence of some rare cosmic phenomena print out c
putchar(c);
}
}
// getcharc doesn't take an argument
int getcharc ()
{
int c; // we declare another c
c = getchar(); // we read from the keyboard a character
printf("\n"); // we print a newline
return 0; // we return 0 which anyway will never be read by anyone
}
maybe you are getting confused with the old K&R
nowadays when you write a function argument you specify it like
int getcharch(int c)
{
...
}

C Program that counts Words and Lines in Standard input

I am new to C programming and I am currently trying to teach myself how to create a C program that can count words and lines in the input stream and print the two totals to the standard output.
What I am actually trying to do is to have the program count the number of lines and count the number of words depending on the definition of a word in which I feel that I am off.
I want the words to exclude blanks, tabs, newlines, hyphens, or colons. While having the program output the results (words and lines) as decimals.
#include<stdio.h>
int main()
{
int iochar;
int words;
int lines;
printf("Enter something here:\n\n");
while ((iochar = getchar ()) !=EOF)
{
if((iochar == ' ') || (iochar == '\t') || (iochar == '\n'))
putchar(iochar);
}
return 0;
}
Am I totally off on this program?
If your question is how to fix the compile error, that's simple. Add one more closing brace at the end.
But your program will still do only one pass through the loop and will print only one character if and only if the user types a space, tab or newline. No matter what the user types, the program will then terminate. I doubt that's what you wanted.
I suspect this is what you intended:
while ((iochar = getchar ()) !=EOF)
{
if((iochar == ' ') || (iochar == '\t') || (iochar == '\n'))
{
putchar(iochar);
}
}
return 0;
After your "I am trying to have thee numbers be right justified in an 8-column field ..." I cannot understand what you are trying to say :(
int words = 0;
int lines = 0;
char buffer[1024];
while(fgets(buffer, sizeof buffer, stdin))
{
lines++;
if(buffer[0] == '\n')
continue;
char *tmp = buffer-1;
while(tmp = strchr(tmp+1, ' '))
words++;
words++; /* count last word before \0*/
}
printf("lines: %d, words: %d\n", lines, words);
is that what you need/want?
The error message is:
Test.c:20:1: error: expected declaration or statement at end of input
It does not compile because you are missing a }.
Had you properly indented your code, like so, you would have found your mistake:
#include<stdio.h>
int main() {
int iochar;
int words;
int lines;
printf("Enter something here:\n\n");
while ((iochar = getchar ()) !=EOF)
{
if((iochar==' ')||(iochar=='\t')||(iochar=='\n'))
{
putchar(iochar);
iochar = getchar();
}
return 0;
}
Yet another example of the importance of readability :)

Resources