Program to show the number of characters in a string - c

This is a program to find the number of characters in a string. But it counts the wrong number of characters. Is it counting the white space too ? Even if that is true how can the total number be 89 ? (see output below)
#include <stdio.h>
#include <conio.h>
void occurrence(char str[100], char ch)
{
int count=0,max =0,i;
for(i=0;i<=100;i++)
{
if(str[i]!='\0')
{
max = max + 1;
if(str[i]==ch)
{
count = count + 1;
}
}
}
printf("\nTotal Number of characters : %d\n",max);
printf("\nNumber of Occurrences of %c : %d\n",ch,count);
}
int main(void)
{
void occurrence(char [], char);
int chk;
char str[100], ch, buffer;
clrscr();
printf("Enter a string : \n");
gets(str);
printf("Do you want to find the number of occurences \nof a particular character (Y = 1 / N = 0) ? ");
scanf("%d", &chk);
do
{
if (chk==1)
{
buffer = getchar(); //dummy varaiable to catch input \n
printf("Enter a Character : ");
ch = getchar();
occurrence(str,ch);
printf("\n\nDo you want to check the number of occurences \nof another character (Y = 1 / N = 0) ? ");
scanf("%d", &chk);
}
else
{
exit();
}
}
while(chk);
return 0;
}

There are two important things wrong with the for loop that counts characters:
It goes from 0 to 100, when it should go from 0 to 99. If you allocate a 100-element array, then the index of the highest element is 99, for a total of a hundred elements. Traditionally the exit condition for the loop would be i < 100, not i <= 100.
It keeps going after the '\0' is found. The '\0' character marks the end of the string, and you should not count any characters after it. Some of the characters after the '\0' may themselves be '\0's, and so you won't count them; but there could be any other kind of garbage there as well, and those will mess up your count. You must figure out how to change your for loop to exit as soon as the '\0' character is found, and not count anything else after that point.

Yes, whitespace is a character. Also are characters each of the 100 elements in your array. You are counting everything but nulls, sp I guess you have 11 nulls. Also, your for loop is off by one.

This will give you correct output.
void occurrence(char str[100], char ch)
{
int count=0,max = 0,i = 0;
while(str[i]!='\0')
{
max = max + 1;
if( str[i] == ch )
{
count = count + 1;
}
i++;
}
}

Related

how to use scanf with integers or a char in c

Basically I have a simple loop that has a scanf
int main(void){
int num, i;
for(i=0; i<100; i++){
printf("enter a number or Q to quit");
scanf("%d",&num);
}
}
How can I use scanf with integers to keep the loop going and for the Chars 'Q' and 'q' to stop the loop by setting i to 100.
Can't claim that this will work in all cases, but it seems to work for me.
int main() {
int num, i;
char q;
for( i = 0; i < 100; i++ ) {
printf("enter a number or Q to quit: ");
if( scanf("%d",&num) != 1 ) {
scanf( " %c", &q );
printf( "picked up %c\n", q );
}
printf("number %d\n", num );
}
return 0;
}
enter a number or Q to quit: 42
number 42
enter a number or Q to quit: 27
number 27
enter a number or Q to quit: q
picked up q
number 27
It's not very good code... You really should use fgets() and interpret whatever buffer load you get from the user.
Here's my solution, similar to what Fe2O3 did:
#include <stdio.h> // IO
#include <stdbool.h> // Boolean values
int main(void)
{
int value; // Integer value
char ch; // Character value
bool ended = false; // Loop ended state
const unsigned int END_CH_LEN = 2; // Length of ending characters array
char stop_ch[END_CH_LEN] = {'q', 'Q'}; // Ending characters
for (int i = 0; i < 100; i++)
{
// Check loop ended state
if (ended)
{
break;
}
// Print prompt
printf("Enter a number or quitting character (q / Q): ");
// Try to read integer, and check if the value is integer
if (scanf("%d", &value) != 1)
{
// Read character
scanf("%c", &ch);
// Check for ending characters
for (unsigned int i = 0; i < END_CH_LEN; i++)
{
// If match detected
if (ch == stop_ch[i])
{
// Exit loop
ended = true;
break;
}
}
}
else
{
// Print integer
printf("Integer value: %d\n", value);
}
}
return 0;
}
But still, as Fe2O3 previously mentioned, this code is not very scalable; the expected integer is fixed in size, and depending on the return value of scanf to detect non-numerical inputs may break things in the future. If possible, read everything into a string first, then use something like strtol for integer conversion, coupled with dynamic memory allocation for variable-sized strings if needed.

Counting Characters and Strings n C

This is one of the assignments for my class and this is the objective of the assignment:
Write a program whose input is a character and a string, and whose output indicates the number of times the character appears in the string. The output should include the input character and use the plural form, n's, if the number of times the characters appears is not exactly 1. You may assume that the string does not contain spaces and will always contain less than 50 characters.
This is the code I have so far and I am new to C programming so I don't know how to declare Strings correctly just yet. So far I learned there are no strings in C like there is in Java and you have to do them as a character array:
#include <stdio.h>
#include <string.h>
int main(void) {
char userChar;
char userString[50];
int count = 0;
for (int i = 0; i < userChar; i++) {
if (userString[i] == userChar)
count++;
}
printf("%d", count);
if (count != 1)
printf("'s");
return 0;
}
For example, if I wanted to input n Monday and output 1 n
What would I need to change in my code to go from n Monday to 1 n
This is the only output I am getting, and it only has outputted one thing correctly:
0's
First, I hope this is not considered cheating :-)
Second, you need to define userChar and userString as arguments for main, and pass them in at run time. They are assigned nothing, so that is why you get
0's
Third, your for condition is wrong. You need this so it only iterates through the length of the string:
for (int i = 0; i < strlen(userString); i++)
Finally, You are not printing the value of userChar prior to the return
At first you need to input a string and a character. To count the number of occurrences of the character in the string you can use standard string function strchr.
The program can look something like the following
#include <stdio.h>
#include <string.h>
int main(void)
{
char userChar = ' ';
char userString[50] = "";
printf( "Enter a string without embedded spaces\nof the length less than %d: ", 50 );
scanf( "%49s", userString );
printf( "Enter a character to search in the string: " );
scanf( " %c", &userChar );
size_t n = 0;
for ( const char *p = userString; ( p = strchr( p, userChar ) ) != NULL; ++p )
{
++n;
}
printf( "%zu%s %c\n", n, n < 2 ? "" : "'s", userChar );
}
The expected output is not 0's, it should include the counted character: for example if the character is n and the string Monday, the output should be
1 n
and if the string is Eeny-meeny-miny-moe, the output would be
3 n's
Here is a modified version:
#include <stdio.h>
int main() {
char userChar;
char userString[50];
int i, count;
printf("Enter character: ");
scanf(" %c", &userChar);
printf("Enter string (single word): ");
// read a word with at most 49 characters
scanf(" %49s", userString);
count = 0;
for (i = 0; userString[i] != '\0'; i++) {
if (userString[i] == userChar)
count++;
}
printf("%d %c", count, userChar);
if (count != 1)
printf("'s");
printf("\n");
return 0;
}

word entry in an array of strings

I'm trying to make a program that will read up to 20 words entered by the user and stored in an array of strings. The program will ask for additional words until 20 words have been entered or until the word 'done' has been entered. The idea is that these words will then be entered into a matrix to create a word search program. I'm stuck on scanning in the words entered by the user. I'm a new programmer so any words of advice is very beneficial.
#include <stdio.h>
int main(void)
{
char string[20][100];
printf("Enter up to 20 words to hide in the puzzle.\n");
printf("Enter the word 'done' after your last word if entering less than 20 words.\n");
scanf("%s\n",c)
printf("Entered words:\n");
return 0;
}
#include<stdio.h>
#include<string.h>
int main(void)
{
char words[20][100];
char temp[100]="\0";
int i=0;
int end=0; //0 false and 1 true
printf("Enter 20 words or enter done to exit.\n");
while(i <=19 && end==0)
{
strset(temp,'\0');// resets array temp to NULL's everytime
scanf(" %99[^\n]",temp); //this is scan set, to read a string without '\n'
printf("Given:%s\n\n",temp);
if(strcmpi(temp,"done")==0)//compares given input with "done".if "done" is entered. zero is returned
end=1;//when 0 is returned this end=1 will break the loop.
else//if input is not given "done" then copy temp array to words[i].
{
strcpy(words[i],temp);
i++;
}
}
}
Instead of using words[20][100] directly, I have used a temporary array named temp to initially store the input,because at the end i don't want to store "done" into words[20][100].Assuming that "done" is used only to end the input process and it is not the actual word to store.But you can change this program to your need.
This is a straight-forward but bug-fixed variant of the code provided by developer3466402 in his answer.
I've used a for loop instead of a while loop since that neatly summarizes the action in the while loop. I added n to record how many words were entered, leaving i as a loop control variable (yes, once upon a long time ago I wrote Fortran too).
#include <stdio.h>
#include <string.h>
int main(void)
{
char words[20][100];
int i = 0;
int n;
printf("Enter up to 20 words to hide in the puzzle.\n");
printf("Enter the word 'done' after your last word if entering less than 20 words.\n");
for (i = 0; i < 20; i++)
{
printf("Enter word %2d:\n", i+1);
if (scanf("%99s", words[i]) != 1 || strcmp(words[i], "done") == 0)
break;
}
n = i;
printf("%d words entered\n", n);
for (i = 0; i < n; i++)
printf("Word %2d = [%s]\n", i+1, words[i]);
return 0;
}
It worked OK for me entering 0, 1, many and 20 words. We can debate the newline after the prompt; it has pros and cons, but that's generally true. I chose to echo the data after the loop rather than within the loop. Be aware that with some programs, echoing in a loop can appear to work where echoing after the loop shows a problem.
Example run (with an early exit):
$ ./rw
Enter up to 20 words to hide in the puzzle.
Enter the word 'done' after your last word if entering less than 20 words.
Enter word 1:
aleph
Enter word 2:
null
Enter word 3:
absolute
Enter word 4:
twaddle and nonsense
Enter word 5:
Enter word 6:
Enter word 7:
elephants are done for
Enter word 8:
Enter word 9:
8 words entered
Word 1 = [aleph]
Word 2 = [null]
Word 3 = [absolute]
Word 4 = [twaddle]
Word 5 = [and]
Word 6 = [nonsense]
Word 7 = [elephants]
Word 8 = [are]
$
You can dynamically allocate memory to store words. If the user inputs more than 20 words, then you can use realloc function to allocate more memory.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
int wlimit = 20;
int wcount = 0;
int retval; // to save the return value of scanf
char wstring[100+1]; // +1 for the terminating null byte
char **wlist = malloc(wlimit * sizeof *wlist);
if(wlist == NULL) {
// handle it
printf("not enough memory to allocate\n");
return 1;
}
char *temp;
while(1) {
if(wcount >= wlimit) {
wlimit *= 2;
temp = wlist;
wlist = realloc(wlist, wlimit);
if(temp == NULL) {
printf("not enough memory to allocate\n");
wlist = temp;
}
}
retval = scanf("%100s", wstring);
// if the input string is done, then break out of the
// loop else keep taking input from the user
if(retval != 1 || strcmp(wstring, "done") == 0)
break;
// strdup function creates a new string which is a duplicate
// of the input string and returns a pointer to it which can
// be freed using free
wlist[wcount++] = strdup(wstring);
}
// do stuff with wlist
// after done, free the memory
for(int i = 0; i < wcount; i++)
free(wlist[i]);
free(wlist);
wlist = NULL;
// stuff
return 0;
}
I think you wish something like below:
#include<stdio.h>
int main(void)
{
char words[20][100];
int i = 0;
printf("Enter up to 20 words to hide in the puzzle.\n");
printf("Enter the word 'done' after your last word if entering less than 20 words.\n");
while (i < 20) {
printf("Entered words:\n");
if (scanf("%99s", words[i]) != 1 || strcmp(words[i], "done") == 0)
break;
printf("%s\n", words[i]);
i++;
}
return 0;
}

Check if input is a string (4 characters only) and if not return to input again

My aim is to accept 4-digit numbers, and 4-character strings (string should not contain digits or special characters)
If an invalid input is given the program should not terminate and it must allow the user to enter the details and continue until he wish to terminate.
I am able to find whether the input is a digit.
if(scanf("%d",&input)!=1)
{
printf("enter the number please");
... // I have option to re enter using while and flags
}
else
{
// I continue my work
...
}
To check it is four digits I have tried using the commands
i=0;
num = input;
while(num>0)
{
i = i+1;
num = num/10;
}
if(i==4){
...//I continue
}
else
printf("please enter four digit");
I have no idea of checking the same for characters. (I know how to check its length using strlen())
Please help me with the code in C. (Also help me to reduce/optimize the above logic to check whether the input is a 4-digit number)
I believe you want 2 inputs a number and a string. You can do that as
int number= 0;
char string[10] = { 0 };
do {
printf("please enter four digit");
scanf("%d", &number);
if(number >=1000 && number<= 9999)
break;
} while(1);
do {
printf("please enter four character string");
fgets(string, sizeof(string), stdin);
if(strlen(string) == 4)
break;
} while(1);
To check it is four digit number you can simply put a check whether the number lies between 1000 and 9999. (I am assuming you don't want the number to start with 0.)
strtol can help:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char s[32], *p;
int x;
fgets(s, sizeof(s), stdin);
if ((p = strchr(s, '\n')) != NULL)
*p = '\0';
x = (int)strtol(s, &p, 10);
if ((p - s) == 4) {
printf("%d\n", x);
} else {
printf("Please enter four digit\n");
}
return 0;
}
char input[16];
int ok = 1, k = 0;
if (scanf("%s", input) > 0 && strlen(input) == 4) {
// check if it's a word
for (; k < 4; k++)
if (!isalpha(input[k])) {
// check if it's a number
for (int k = 0; k < 4; k++)
if (!isdigit(input[k]))
ok = 0;
break;
}
}
else ok = 0;
if (!ok)
printf("invalid input, please enter a 4-digit number or 4-letter word");
else {
printf("valid input");
...
}
You can use gets()1 fgets() to get the whole line and check line length. If the first character is between '0' and '9' then check the remaining if they are 3 numbers too. If the first character is a valid character in string then check the 3 remaining chars if it's also valid in string.
1See Why is the gets function so dangerous that it should not be used?

How to count the number of words that contain at least 3 vowels

I was wondering if I could ask for some help. I am writing a program in C that writes out the number of characters, words, and vowels are in the string(with a few added print statements). I am trying to figure out how to write a code that loops through the string and counts the number of words that contain at least 3 vowels. I feel as if this is a very easy code to write, but it's always the easiest things that seem to elude me. Any help?
Also: Being new to C, how can I get the same results while using the function int vowel_count(char my_sen[]) instead of using the code within my main?
If that's a tad confusing I mean since my main already contains code to count the number of vowels within my input, how can I somewhat transfer said code into this function and still call upon it in main?
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define SENTENCE 256
int main(void){
char my_sen[SENTENCE], *s; //String that containts at most 256 as well as a pointer
int words = 1, count = 0,vowel_word = 0; //Integer variables being defined
int i,vowel = 0, length; //More definitions
printf("Enter a sentence: ");//Input sentence
gets(my_sen);//Receives and processes input
length = strlen(my_sen); //Stores the length of the input within length
for(i=0;my_sen[i] != '\0'; i++){
if(my_sen[i]=='a' || my_sen[i]=='e' || my_sen[i]=='i' || my_sen[i]=='o' || my_sen[i]=='u' || //Loop that states if the input contains any of the following
my_sen[i]=='A' || my_sen[i]=='E' || my_sen[i]=='I' || my_sen[i]=='O' || my_sen[i]=='U') //characters(in this case, vowels), then it shall be
{ //stored to be later printed
vowel++;
}
if(my_sen[i]==' ' || my_sen[i]=='!' || my_sen[i]=='.' || my_sen[i]==',' || my_sen[i]==';' || //Similar to the vowel loop, but this time
my_sen[i]=='?') //if the following characters are scanned within the input
{ //then the length of the characters within the input is
length--; //subtracted
}
}
for(s = my_sen; *s != '\0'; s++){ //Loop that stores the number of words typed after
if(*s == ' '){ //each following space
count++;
}
}
printf("The sentence entered is %u characters long.\n", length); //Simply prints the number of characters within the input
printf("Number of words in the sentence: %d\n", count + 1); // Adding 1 to t[he count to keep track of the last word
printf("Average length of a word in the input: %d\n", length/count);//Prints the average length of words in the input
printf("Total Number of Vowels: %d\n", vowel);//Prints the number of vowels in the input
printf("Average number of vowels: %d\n", vowel/count);//Prints the average number of vowels within the input
printf("Number of words that contain at least 3 vowels: %d\n", vowel_word);//Prints number of words that contain at least 3 vowels
return 0;
}
It's not much of a problem.
#include <ctype.h>
#include <stdio.h>
#include <string.h>
int vowel_count(char my_sen[])
{
int wcount = 0; // number of words with 3+ vowel chars
int vcount = 0; // current number of vowel chars in the current word
int i = 0; // index into the string
int ch;
while ((ch = my_sen[i++]) != '\0')
{
if (isspace(ch) || !isalpha(ch))
{
// ch is not an alphabetical char, which can happen either
// before a word or after a word.
// If it's after a word, the running vowel count can be >= 3
// and we need to count this word in.
wcount += vcount >= 3; // add 1 to wcount if vcount >= 3
vcount = 0; // reset the running vowel counter
continue; // skip spaces and non-alphabetical chars
}
if (strchr("aeiouAEIOU", ch) != NULL) // if ch is one of these
{
++vcount; // count vowels
}
}
// If my_sen[] ends with an alphabetical char,
// which belongs to the last word, we haven't yet
// had a chance to process its vcount. We only
// do that in the above code when seeing a non-
// alphabetical char following a word, but the
// loop body doesn't execute for the final ch='\0'.
wcount += vcount >= 3; // add 1 to wcount if vcount >= 3
return wcount;
}
int main(void)
{
char sen[] = "CONSTITUTION: We the People of the United States...";
printf("# of words with 3+ vowels in \"%s\" is %d", sen, vowel_count(sen));
return 0;
}
Output (ideone):
# of words with 3+ vowels in "CONSTITUTION: We the People of the United States..." is 3
Btw, you can alter this function to count all things you need. It already finds where words begin and end and so, simple word counting is easy to implement. And word length, too. And so on.
1) Get the string,
2) use strtok () to get each words seperated by space.
3) Loop through each string by char by char to check if it is vowel.
Please check below code
#include<stdio.h>
#include <string.h>
int count_vowels(char []);
int check_vowel(char);
main()
{
char array[100];
printf("Enter a string\n");
gets(array);
char seps[] = " ";
char* token;
int input[5];
int i = 0;
int c = 0;
int count = 0;
token = strtok (array, seps);
while (token != NULL)
{
c = 0;
c = count_vowels(token);
if (c >= 3) {
count++;
}
token = strtok (NULL, seps);
}
printf("Number of words that contain atleast 3 vowels : %d\n", count);
return 0;
}
int count_vowels(char a[])
{
int count = 0, c = 0, flag;
char d;
do
{
d = a[c];
flag = check_vowel(d);
if ( flag == 1 )
count++;
c++;
}while( d != '\0' );
return count;
}
int check_vowel(char a)
{
if ( a >= 'A' && a <= 'Z' )
a = a + 'a' - 'A'; /* Converting to lower case */
if ( a == 'a' || a == 'e' || a == 'i' || a == 'o' || a == 'u')
return 1;
return 0;
}

Resources