#include <stdlib.h>
#include <ctype.h>
#include <stdio.h>
int main()
{
unsigned long c;
unsigned long line;
unsigned long word;
char ch;
c = 0;
line = 0;
word = 0;
printf("Please enter text:\n");
while((ch = getchar()) != EOF)
{
c ++;
if (ch == '\n')
{
line ++;
}
if (ch == ' ' || ch == '\n')
{
word ++;
}
}
printf( "%lu %lu %lu\n", c, word, line );
return 0;
}
Right now my program works and it counts correctly for characters, words, and lines. But for words like That's, the program counts it as 1 word and I want it to count as 2 words. What would I need to add to account for that?
if(ch =='\'' || ch == ' ' || ch == '\n')
{
word++;
}
Related
I have experienced some problem with segmentation when I'm learning through C, my aim is to swap the tabs in the program with spaces:
I have used the get_line template and modified the code to suit the situation. Here is the whole coded solution:
#include <stdio.h>
#define MAXLINE 1000
char line[MAXLINE];
char detabline[MAXLINE];
int get_line(void);
int main(void){
int len;
int i;
int nt = 0;
extern char detabline[];
extern char line[];
while ((len = get_line()) > 0){
for (i = 0; i < len; ++i){
if (line[i] == '\t'){
printf("%s", " ");
}
else{
printf("%s", line[i]);
}
}
}
return 0;
}
int get_line(void){
int c, i, nt;
nt = 0;
extern char line[];
for (i = 0; i < (MAXLINE - 1) && (c = getchar()) != EOF && ((c != '\t') || (c != '\n')); ++i){
line[i] = c;
}
if (c == '\n'){
line[i] = c;
++i;
}
else if (c == '\t'){
++nt;
}
line[i] = '\0';
return i;
}
The problem is to locate which memory isn't allocated correctly. I may have some redundant code in the solution by the way.
regarding:
for (i = 0; i < (MAXLINE - 1) && (c = getchar()) != EOF && ((c != '\t') || (c != '\n')); ++i){
this expression:
(c != '\t')
will result in no tab character ever being in the line[] array.
this expression:
(c != '\n')
will result in no newline character sequence ever being in the line[] array.
then, due those expressions, the line[] array will not be updated (ever again) when a tab or a newline is encountered due to those expressions causing an early exit from the for() loop
The following proposed code:
cleanly compiles
performs the desired functionality
and now, the proposed code:
#include <stdio.h>
#define MAXLINE 1000
char line[MAXLINE];
int main(void)
{
int i = 0;
int ch;
while ( i< MAXLINE-1 && (ch = getchar()) != EOF && ch != '\n' )
{
if ( ch == '\t')
{
line[i] = ' ';
}
else
{
line[i] = (char)ch;
}
i++;
}
printf( "%s\n", line );
}
Post a comment if you want further details about the proposed code.
For my assignment I need to modify the following program. I can not use strings.h.
int main(void)
{
int c, countSpaces = 0;
printf("Type sentence:\n");
do
{
c = getchar();
if (c == ' ')
countSpaces = countSpaces + 1;
}
while (c != '\n');
printf("Sentence contains %d Spaces.\n", countSpaces);
return 0;
}
I tried using
if (c != EOF)
countSpaces = countSpaces + 1;
}
while (c != '\n');
printf("Sentence contains %d Spaces.\n", countSpaces - 1);
but that seems like a hacky and unelegant way to do this.
Can anyone help and/or explain to me how to do this better?
Thanks in advance
The code I posted counts the spaces in a sentence, I want to modify it to count all the characters in the input sentence. – fbN 21 secs ago
Have another counter outside the if condition.
#include <stdio.h>
int main(void)
{
int c;
int countSpaces = 0;
int countChars = 0;
puts("Type sentence:");
do {
c = getchar();
countChars += 1;
if (c == ' ') {
countSpaces += 1;
}
} while (c != '\n');
printf("Sentence contains %d spaces and %d characters.\n", countSpaces, countChars);
return 0;
}
Two notes. foo += 1 is shorthand for foo = foo + 1 without the precendence complexities of foo++.
Blockless if or while is playing with fire. Eventually you'll accidentally write this.
if( condition )
do something
whoops this is not in the condition but it sure looks like it is!
Always use the block form.
$ ./test
Type sentence:
foo bar baz
Sentence contains 2 spaces and 12 characters.
Note this says 12 because it's including the newline. That's because it's checking what c is after it's already been counted. You can fix this by checking c as its read. This is a fairly normal "read and check" C loop idiom.
// Note, the parenthesis around `c = getchar()` are important.
while( (c = getchar()) != '\n' ) {
countChars++;
if (c == ' ') {
countSpaces++;
}
}
$ ./test
Type sentence:
foo bar baz
Sentence contains 2 spaces and 11 characters.
I always prefer to use fgets() when reading a line from the console (stdin):
#include <stdio.h>
int main(void)
{
int i;
int length = 0;
char buffer[1024];
printf( "Enter some text> " );
fgets( buffer, sizeof(buffer), stdin );
// If the user inputs > 1024 letters, buffer will not be \n terminated
for ( i=0; buffer[i] != '\n' && buffer[i] != '\0'; i++ )
{
length += 1;
}
printf( "length: %d\n", length );
return 0;
}
I make this code that count length of the string given It's like strlen function.
and I used just scanf and it works perfectly even with spaces.
#include <stdio.h>
int main()
{
char *str = calloc(sizeof(char),50);
int i = 0, count = 0;
printf("Type sentence:\n");
scanf("%[^\n]",str);
while (str[i++] != '\0')
count++; //length of the string
printf("%d",count);
return 0;
}
and if you want just to count the characters in the string given use this code below:
#include <stdio.h>
int main()
{
char *str = calloc(sizeof(char),50);
int count = 0;
printf("Type sentence:\n");
scanf("%[^\n]",str);
for (int i = 0; str[i] != '\0'; i++)
if ((str[i] >= 'A' && str[i] <= 'Z') || (str[i] >= 'a' && str[i] <= 'z'))
count++;
printf("Sentence contains %d characters.\n",count);
return 0;
}
the output :
Type sentence:
hello world
Sentence contains 10 characters.
you can just calculate the result like this
int main(void)
{
int c, countSpaces = 0;
printf("Type sentence:\n");
do
{
c = getchar();
if (c == ' ')
countSpaces++;
}
while (c != '\n');
int countChar = c - countSpaces - 1 ; // -1 new line
printf("Sentence contains %d Spaces.\n", countSpaces);
printf("Sentence contains %d chars.\n", countChar);
return 0;
}
I want to count the number of words, characters, new lines, no matter how my sentence looks like. (For example, even if I typed a sentence like this:
y yafa \n \n youasf\n sd
the program should still be able to count the number of words, lines, characters correctly). I don't know how to implement such program with pure C, can anyone help me on that?
Here is my current code, and it can only be correct under certain conditions...
int main() {
int cCount = 0, wCount = 0, lCount = 0;
printf("Please enter the sentence you want\n");
char str[20];
int j7 = 0;
while (int(str[j7]) != 4) {
str[j7] = getchar();
if (str[0] == ' ') {
printf("Sentence starts from a word not blank\n");
break;
}
if (int(str[j7]) == 4)
break;
j7++;
}
int count = 0;
while (count < 20) {
if (str[count] != ' ' && str[count] != '\n') {
cCount++;
} else
if (str[count] == ' ') {
wCount++;
} else
if (str[count] == '\n') {
lCount++;
}
count++;
}
printf("Characters: %d\nWords: %d\nLines: %d\n\n",
cCount, wCount++, lCount + 1);
int x = 0;
std::cin >> x;
}
You are not writing in Pure C, but rather in C++.
To achieve your goal, you must summarize the problem into a sequence of logical steps:
for each character read:
if the previous one is a line separator, you have a new line ;
if the previous one is a word separator and the current isn't, you have a new word ;
if all cases, you have a new character, save it as the previous character for the next iteration.
Use '\n' as the initial value for the last character, so the first character read if any starts a new line and possibly a new word if it is not whitespace.
Here is a simple implementation:
#include <ctype.h>
#include <stdio.h>
int main(void) {
long chars = 0, words = 0, lines = 0;
printf("Enter the text:\n");
for (int c, last = '\n'; (c = getchar()) != EOF; last = c) {
chars++;
if (last == '\n')
lines++;
if (isspace(last) && !isspace(c))
words++;
}
printf("Characters: %ld\n"
"Words: %ld\n"
"Lines: %ld\n\n", chars, words, lines);
return 0;
}
If you are required to use a while loop, the for loop can be converted this way:
#include <ctype.h>
#include <stdio.h>
int main(void) {
long chars = 0, words = 0, lines = 0;
int c, last = '\n';
printf("Enter the text:\n");
while ((c = getchar()) != EOF) {
chars++;
if (last == '\n')
lines++;
if (isspace(last) && !isspace(c))
words++;
last = c;
}
printf("Characters: %ld\n"
"Words: %ld\n"
"Lines: %ld\n\n", chars, words, lines);
return 0;
}
basically we are provided with the main function:
#include <stdio.h>
#include <string.h>
#include <strings.h>
#define STORAGE 255
{
int c;
char s[STORAGE];
for(;;) {
(void) printf("n=%d, s=[%s]\n", c = getword(s), s);
if (c == -1)break;
}}
we are not to change that
and we have to create the function getword() which should contain a loop that reads a characters,
store it in a array in the address provided one by one and it should stop for whitespace (tab, space, eof)
basically i have this:
int getword(char *w)
{
char str[255];
int i = 0;
int charCount = 0;
printf("enter your sentence:\n");
gets(str);
/*this was provided by the professor, but i'm not sure how to use it
while (( iochar - getchar()) !=EOF);
*/
for(i = 0; str[i] != '\0'; i++) //loop that checks tab and spaces
{
if(str[i] != ' ' && str[i] != '\t')
{
charCount++;
}
}
printf("your string: '%s' contains %d of letters\n", str, charCount);
return 0;}
right now the output of the program is:
enter your sentence:
hey stockoverflow
your string: 'hey stockoverflow' contains 16 of letters
n=0, s=[]
so i'm saving the string and counting it, but i'm not storing it where i should be.
it should display n=16, s=[hey stockoverflow]
actually it should display n=3, s=[hey]
any help would be appreciated
This may be what you are looking for:
for(i = 0; str[i] != '\0'; i++) //loop that checks tab and spaces
{
if(str[i] != ' ' && str[i] != '\t')
{
charCount++;
}
else
{
str[i] = '\0'; // Terminate str
break; // Break out of the for-loop
}
}
printf("your string: '%s' contains %d of letters\n", str, charCount);
strcpy(w, str); // Add this line to copy str into w (which is s from main)
return strlen(w); // Return the length of the result string
#include <stdlib.h>
#include <stdio.h>
int main()
{
unsigned long c;
unsigned long line;
unsigned long word;
char ch;
c = 0;
line = 0;
word = 0;
while((ch = getchar()) != EOF)
{
c ++;
if (ch == '\n')
{
line ++;
}
if (ch == ' ' || ch == '\n' || ch =='\'')
{
word ++;
}
}
printf( "%lu %lu %lu\n", c, word, line );
return 0;
}
My program works fine for the most part, but when I add extra spaces, it counts the spaces as extra words. So for example, How are you? is counted as 10 words, but I want it to count as 3 words instead. How could I modify my code to get it to work?
I found a way to count words and between them several spaces the program will count only the words and not the several spaces also as words
here is the code:
nbword is the number of words, c is the character typed and prvc is the previously typed character.
#include <stdio.h>
int main()
{
int nbword = 1;
char c, prvc = 0;
while((c = getchar()) != EOF)
{
if(c == ' ')
{
nbword++;
}
if(c == prvc && prvc == ' ')
nbword-;
if(c == '\n')
{
printf("%d\n", nbword);
nbword = 1:
}
prvc = c;
}
return 0:
}
This is one possible solution:
#include <stdlib.h>
#include <stdio.h>
int main()
{
unsigned long c;
unsigned long line;
unsigned long word;
char ch;
char lastch = -1;
c = 0;
line = 0;
word = 0;
while((ch = getchar()) != EOF)
{
c ++;
if (ch == '\n')
{
line ++;
}
if (ch == ' ' || ch == '\n' || ch =='\'')
{
if (!(lastch == ' ' && ch == ' '))
{
word ++;
}
}
lastch = ch;
}
printf( "%lu %lu %lu\n", c, word, line );
return 0;
}
Hope this helped, good luck!