Char Count in C? - c

So I am getting 1 more extra character than I should when i compile this code, someone please tell me the stupid error i am doing.
#include <stdio.h>
#include <conio.h>
int main() {
char str[20];
char A = 'a';
char B = 'A';
int count = 0, i;
printf("Enter a string : ");
fgets(str, 20, stdin);
for (i = 0; str[i] != '\0'; i++) {
if (str[i] == A||B)
count++;
}
if (count == 0)
printf("\nCharacter A is not present");
else
printf("\nThere are %d A's in your string.", count);
getchar();
return 0;
}

/* This is the issue (str[i] == A)||(str[i] == B) */
#include <stdio.h>
#include <conio.h>
int main() {
char str[20];
char A = 'a';
char B = 'A';
int count = 0, i;
printf("Enter a string : ");
fgets(str, 20, stdin);
for (i = 0; str[i] != '\0'; i++) {
if (str[i] == A || str[i] == B)
count++;
}
if (count == 0)
printf("\nCharacter A is not present");
else
printf("\nThere are %d A's in your string.", count);
getchar();
return 0;
}

Related

Program prints the backward version of the given set of words

First I should enter the number of words I am going to print backwards, then enter those words and program should print them line by line backwards, for example:
3
Something
written
backwards
program prints:
gnihtemoS
nettirw
sdrawkcab
This is a piece of code I wrote, I don't really know why it doesn't work. I'm totally newbie in programming, thanks for help.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
int i, j, n;
char str[100]="\0";
char buff[100];
scanf("%d", &n);
printf("Enter String\n");
for(int i=0;i<=n; i++)
{
fgets(buff, sizeof buff, stdin);
strcat(str, buff);
}
printf("\nString in Reverse Order\n");
i = 0;
while(str[i] != '\0')
{
if(str[i] == ' ' || str[i] == '\n')
{
for(j = i - 1; j >= 0 && str[j] != ' '; j--)
printf("%c", str[j]);
}
i++;
}
printf("\n");
return 0;
}
For this input:
3
Enter String
string
written
backwards
this is output:
String in Reverse Order
gnirts
nettirw
gnirts
sdrawkcab
nettirw
gnirts
Ok I got there and now program is working perfectly. Thanks for tips!
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
int i, j, n;
char str[100]="\0";
char buff[100];
scanf("%d", &n);
printf("Enter String\n");
for(int i=0;i<=n; i++)
{
fgets(buff, sizeof buff, stdin);
strcat(str, buff);
}
printf("\nString in Reverse Order\n");
i = 0;
while(str[i] != '\0')
{
if(str[i] == ' ' || str[i] == '\n')
{
for(j = i - 1; j >= 0 && str[j] != ' ' && str[j] != '\n'; j--)
printf("%c", str[j]);
printf("\n");
}
i++;
}
printf("\n");
return 0;
}

Modifying a program to run as command line arguments in C

Full disclosure, this is an assignment for a class I have to do. We have a program that checks if two words are anagrams. We are supposed to modify it so that we can enter the words as command lines in a program. For instance: (./a.out hello elloh: is an anagram... ./a.out hello world: Not an anagram).
Here is the original program:
#include <stdio.h>
#define N 26
int main()
{
char ch;
int letter_counts[N]= {0};
int i;
int count =0;
printf("enter a word: ");
while((ch=getchar())!= '\n')
{
letter_counts[ch - 'a']++;
}
for(i =0;i<N;i++)
printf("%d", letter_counts[i]);
printf("enter the second word: ");
while((ch=getchar())!= '\n')
{
letter_counts[ch - 'a']--;
}
for(i =0;i<N;i++)
printf("%d", letter_counts[i]);
for(i =0;i<N;i++)
if(letter_counts[i]==0)
count++;
if(count == N)
printf("The words are anagrams.\n");
else
printf("The words are NOT anagrams.\n");
return 0;
}
Now here is what I have so far:
#include <stdio.h>
#define N 26
/*
This program is a modified version of anagram.c so that the words run as command-line arguments.
*/
int main(int argc, char *argv[])
{
if(argc != 3)
{
printf("Incorrect number of arguments");
return 0;
}
char ch;
int letter_counts[N]= {0};
int i;
int count =0;
//int k;
//for (k = 1; i < argc; i++)
//{
while((ch=getchar())!= '\n')
{
letter_counts[ch - 'a']++;
}
for(i =0;i<N;i++)
printf("%d", letter_counts[i]);
while((ch=getchar())!= '\n')
{
letter_counts[ch - 'a']--;
}
//for(i =0;i<N;i++)
//printf("%d", letter_counts[i]);
for(i =0;i<N;i++)
if(letter_counts[i]==0)
count++;
int k;
int j;
for (k = 1; i < argc; i++)
{
for (j = 0; j < N; j++)
{
if (count == N)
{
printf("%s and %s are anagrams\n", argv[k], argv[k + 1]);
break;
}
else
printf("The words are NOT anagrams. \n");
}
}
if(count == N)
printf("The words are anagrams.\n");
else
printf("The words are NOT anagrams.\n");
//}
return 0;
}
The output (if the number of arguments is correct) is always :
0000000000000000000000000
0000000000000000000000000
These are anagrams
What am I doing wrong here and what is the best way to go about this?
Thank you for any help I really appreciate it.
You are using getchar() which reads from STDIN, which isn't what you want to do if you're getting your words from command-line arguments. Instead you want to look at argv:
for (char *c = argv[1]; *c != NULL; c++) {
letter_counts[*c - 'a']++;
}
and
for (char *c = argv[2]; *c != NULL; c++) {
letter_counts[*c - 'a']--;
}
More about argc and argv: http://crasseux.com/books/ctutorial/argc-and-argv.html
To not solve your homework for you I'll show you how to use argc and argv on a different program that just checks if the first parameter reversed equals the second:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv)
{
if (argc != 3) {
printf("Usage: %s first_word second_word\n\n", argv[0]);
return EXIT_SUCCESS;
}
char const *first = argv[1];
char const *second = argv[2];
size_t first_length = strlen(first);
size_t second_length = strlen(second);
if (first_length != second_length) {
puts("The words are NOT semordnilaps.\n");
return EXIT_SUCCESS;
}
for (size_t first_index = first_length, second_index = 0; first_index; --first_index, ++second_index) {
if (first[first_index - 1] != second[second_index]) {
puts("The words are NOT semordnilaps.\n");
return EXIT_SUCCESS;
}
}
puts("The words are semordnilaps.\n");
}
Modified program torun from command line argumement. Below is working code snippet for you.
Here we pass two command line arguments with program name. while ((ch = argv[1][len]) != '\0') retrieve the char by char from first arguments and while ((ch = argv[2][len]) != '\0') retrieve the same from the second and rest of the logic remains same.
#include <stdio.h>
#define N 26
int main(int argc, char *argv[])
{
if( argc != 3)
{
printf("Incorrect argumemts\n");
return 0;
}
char ch;
int letter_counts[N]= {0};
int i;
int count =0;
int len=0;
while ((ch = argv[1][len]) != '\0')
{
letter_counts[ch - 'a']++;
len++; /* moving index */
}
for(i =0;i<N;i++)
printf("%d", letter_counts[i]);
len=0;
while ((ch = argv[2][len]) != '\0')
{
letter_counts[ch - 'a']--;
len++; /* moving index */
}
for(i =0;i<N;i++)
printf("%d", letter_counts[i]);
for(i =0;i<N;i++)
if(letter_counts[i]==0)
count++;
if(count == N)
printf("The words are anagrams.\n");
else
printf("The words are NOT anagrams.\n");
return 0;
}

Searching an Array of Strings from User Input in C

I've got this homework assignment where we get the user to enter the amount of lines of strings they desire, they then proceed to enter them which gets stored in a 2D Array (thus creating an array of strings). Then a switch case menu will be displayed which should
Search a character entered by the user, returns the amount of times the character occurred in the array
Search a word entered by the user, returns the amount of times the word occurred in the array
Have the user enter a specified word length and return the amount of times words of the specified length occur.
I have a couple problems with my code. The program runs without errors from the compiler. The searchByCharacter function works fine but the searchByWord only returns a value of 0 regardless of any word inputted and nothing happens after I input a number for the searchByLength function. The program freezes after I enter a length once I select the searchByLength function. I've been at this for a while and I don't know where I'm going wrong.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LINE_LENGTH 80
#define MAX_LINES 10
#define WORD_LENGTH 20
void readText(char text[][MAX_LINE_LENGTH], int n)
{
int i;
printf("Enter %d number of lines:\n", n);
for(i = 0; i < n; i++)
{
scanf(" %[^\n]s", text[i]);
}
}
int searchByCharacter(char text[][MAX_LINE_LENGTH], int n, char c)
{
int i, charCount = 0, j = 0;
for(i = 0; i < n; i++)
{
j = 0;
while(text[i][j] != '\0')
{
if(text[i][j] == c)
{
charCount++;
}
j++;
}
}
return charCount;
}
int searchByWord(char text[][MAX_LINE_LENGTH], int n, char * keyword)
{
int i, wordCount = 0;
for(i = 0; i < n; i++)
{
int j = 0;
int lengthOfWord = 0;
char wordCheck[WORD_LENGTH];
char * currentLine = text[i];
while(currentLine[j] != '\0')
{
if (currentLine[j] == ' ' || currentLine[j] == '\n' || currentLine[j] == ',' || currentLine[j] == '.' ||
currentLine[j] == ';')
{
wordCheck[lengthOfWord] = '\0';
int matchingWord = strcmp(wordCheck, keyword);
if(matchingWord == 0)
{
wordCount++;
}
lengthOfWord = 0;
j++;
continue;
}
wordCheck[lengthOfWord] = currentLine[n];
lengthOfWord++;
j++;
}
}
return wordCount;
}
int searchByLength(char text[][MAX_LINE_LENGTH], int n, int wordLen)
{
int i, lengthCount = 0;
for(i = 0; i < n; i++)
{
int lengthOfWord = 0;
int j = 0;
char * currentLine2 = text[i];
while(currentLine2[j] != '\0')
{
if (currentLine2[j] == ' ' || currentLine2[j] == '\n' || currentLine2[j] == ',' || currentLine2[j] == '.' ||
currentLine2[j] == ';')
{
if(lengthOfWord == wordLen)
{
lengthCount++;
}
lengthOfWord = 0;
n++;
continue;
}
lengthOfWord++;
n++;
}
}
return lengthCount;
}
int main(void)
{
char textInput[MAX_LINES][MAX_LINE_LENGTH];
printf("Enter number of lines (<10): ");
int textLines = 0;
scanf("%d", &textLines);
while(textLines < 1 || textLines > 10)
{
printf("Invalid Input.\n");
printf("Enter number of lines (<10): ");
scanf("%d", &textLines);
}
if(textLines >= 1 && textLines <= 10)
{
readText(textInput, textLines);
int menuActive = 1;
while(menuActive)
{
printf("\nText Analysis\n----\n");
printf("1-Search By Character\n2-Search By Word\n3-Search By Length\n0-Quit\nPlease enter a selection: ");
int selection;
scanf("%d", &selection);
switch(selection)
{
case 0:
menuActive = 0;
break;
case 1:
printf("Selected 1\n");
printf("Enter a character to search: ");
char characterSearch;
scanf(" %c", &characterSearch);
int characterwordCount = searchByCharacter(textInput, textLines, characterSearch);
printf("\nNumber of occurence of %c = %d", characterSearch, characterwordCount);
break;
case 2:
printf("Selected 2\n");
printf("Enter a word to search: ");
char wordSearch[MAX_LINE_LENGTH];
scanf(" %s", wordSearch);
int lengthwordCount = searchByWord(textInput, textLines, wordSearch);
printf("\nNumber of occurence of %s = %d", wordSearch, lengthwordCount);
break;
case 3:
printf("Selected 3\n");
printf("Enter search length: ");
int wordLength;
scanf(" %d", &wordLength);
int wordLengthwordCount = searchByLength(textInput, textLines, wordLength);
printf("Number of words with length %d = %d", wordLength, wordLengthwordCount);
break;
default:
printf("Invalid Input.\n");
}
}
printf("You Have Quit!\n");
}
return 0;
}

I can't read the second string, no matter how many getchar i insert

This program need to read two strings, this two strings will be passed to the "confirm" function, they will be read and the the function will have to find a word in common.
But in the main i cant read the "string2" string! No matter how many getchar i insert.
#include <stdio.h>
#include <string.h>
void confirm(char string1[],char string2[]){
char word[20];
char w_aux[20];
int i, j, k, l, m;
int len1, len2;
int find;
i = 0;
len1 = strlen(string1);
len2 = strlen(string2);
while (i < len1){
j = 0;
while ((string1[i] != ' ') && (i < len1)){
word[j] = string1[i];
i++;
j++;
}
word[j] = '\0';
k = 0;
find = 0;
while((k < len2) && (find == 0)){
l = 0;
while ((string2[k] != ' ') && (k < len2)){
w_aux[l] = string2[k];
k++;
l++;
}
w_aux[l] = '\0';
if (j == l){
m = 0;
while((word[m] == w_aux[m]) && (m<j)){
m++;
}
if (m == j){
find = 1;
}
}
k++;
}
i++;
}
printf("%s\n", word);
}
int main (){
char string1[20];
char string2[20];
printf("Type the first text: \n");
scanf("%[^\n]s", string1);
printf("Type the second text: \n");
scanf("%[^\n]s", string2);
getchar();
confirm(string1, string2);
return 0;
}
Use getchar after input of string 1 for \n:
printf("Type the first text: \n");
scanf("%[^\n]", string1);
getchar(); //here
printf("Type the second text: \n");
scanf("%[^\n]", string2);
Just change the format specifier to "%19[^\n]*c", it will take the trailing '\n' character away.

Find sum where user has to enter a command with parameters such as 'sum(par1, par2,...)'

User enters command with parameters.There are no errors, but I am having trouble with the weird output.
I took input as string, identified if the input matches the command 'sum', if it does then extracted the parameters in between sum[], stored them in an array and send them as arguments to sum function.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int sumOfArray(int arr[])
{
int sum=0;
for(int i=0;i++;i<sizeof(arr))
{
sum = sum + arr[i];
}
printf("%d\n",sum);
return sum;
}
int main()
{
char input[256];
int j=0,temp=0;
int arraySum[6]={0};
printf("user_account $> ");
fgets(input, sizeof(input), stdin);
if (input[0]=='s' && input[1]=='u' && input[2]=='m')
{
if (input[3]!='(')
{
printf("Please enter proper parameters : sum(num1, num2, ..)\n");
}
else
{
for (int i = 4; i++; input[i] < ']')
{
if (input[i] !=',')
{
if (!isdigit(input[i]))
{
printf("Please enter only digits\n");
break;
}
else
{
temp = int(input[i]);
printf("%d\n",temp);
arraySum[j] = arraySum[j]*10 + temp;
}
}
else j++;
}
}
sumOfArray(arraySum);
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int sumOfPara(void){
int v, sum = 0;
char ch;
while(1){
if(2 == fscanf(stdin, "%d %c", &v, &ch) && (ch == ',' || ch == ')')){
sum += v;
if(ch == ')')
break;
} else {
fprintf(stderr, "Parameter is invalid.\n");
exit(EXIT_FAILURE);
}
}
return sum;
}
int main(void){
char command[32];
char left_paren;
printf("user_account $> ");
if(2 != fscanf(stdin, "%31[a-z] %c", command, &left_paren) || strcmp(command, "sum") != 0 || left_paren != '('){
fprintf(stderr, "Please enter proper parameters : sum(num1, num2, ..)\n");
exit(EXIT_FAILURE);
} else { //rest
printf("%d\n", sumOfPara());
}
return 0;
}

Resources