char search in a string - c

Can anybody help me with my code
int main(void){
int ctr,wordLength;
char theWord[99];
ctr = 0;
printf("Enter a Word: ");
scanf("%s", & );
printf("Enter the letter you want to find: ");
scanf("%s", & );
while(ctr < wordLength | theWord[ctr]=='a'){
ctr++;
}
//output
}
expecting output
Enter a Word: hello
Enter the letter you want to find: z
the letter z is not found in the word.

You can do it this way also,
#include <stdio.h>
int main(void)
{
int ctr;
char theWord[99], ch;
ctr = 0;
printf("Enter a Word: ");
scanf("%s", theWord);
printf("Enter the letter you want to find: ");
scanf(" %c", &ch );
for(int i = 0; theWord[i]; i++)
{
if(theWord[i] == ch)
ctr++;
}
if(ctr != 0)
printf("word is found\n");
else
printf("word is not found\n");
}
Yes, we can do it it using while loop also,
int i = 0;
while(theWord[i] != '\0' )
{
if(theWord[i] == ch)
ctr++;
i++;
}
if(ctr != 0)
printf("word is found\n");
else
printf("word is not found\n");

Corrected code
int main (void)
{
int ctr = 0;
int wordLength;
char theWord[99], ch;
printf("Enter a Word: ");
scanf("%s", theWord);
printf("Enter the letter you want to find: ");
scanf("%c", &ch);
while (theWord [ctr] != '\0')
{
if (theWord [ctr] == ch)
{
print("Character found at position %1", ctr);
break;
}
ctr++;
}
if (theWord [ctr] == '\0')
{
printf ("Character not found");
}
}

I did correction of your code, It works successfully with GCC
#include<stdio.h>
#include <string.h>
int main(void){
int ctr = 0,c = 0, wordLength;
char ch, theWord[99];
printf("Enter a Word: ");
scanf("%s", theWord);
printf("Enter the letter you want to find: ");
scanf("%c", & ch);
wordLength = strlen(theWord);
while(theWord[ctr] != '\0')
{
if (theWord[ctr] == ch)
{
printf("the letter %c is found in the word\n", ch);
c++;
}
ctr++;
}
if (c == 0 )
{
printf("the letter %c is NOT found in the word\n", ch);
}
}

Related

Repeat the Program for again Search Array Element

Repeat the Program for again Search Array Element.
#include <stdio.h>
#define MAX_SIZE 100
int main()
{
int arr[MAX_SIZE];
int size, i, toSearch, found;
char repeat;
printf("Enter the size of an array\n");
scanf("%d", &size);
printf("Enter the array elements\n");
for (i = 0; i < size; i++)
{
scanf("%d", &arr[i]);
}
do{
printf("\nEnter element to search: ");
scanf("%d", &toSearch);
found = 0;
for(i=0; i<size; i++)
{
if(arr[i] == toSearch)
{
found = 1;
break;
}
}
if(found == 1)
{
printf("\n%d is found at position %d", toSearch, i + 1);
}
else
{
printf("\n%d is not found in the array \n", toSearch);
}
printf("\n \n \nPress Y to again Search Any Element in Array\n \nPress Any other Key to Exit the Program\n\n");
scanf(" %c \t",&repeat);
}
while(repeat == 'y' || repeat == 'Y' );
return 0;
}
I want to repeat my program when user give the input of Y || y otherwise it'll exit the program.
In this code i want to make an array then search the element after this show's the results and in last repeat the code from the search the element block.
I ran your code and everything seems to be working properly except for this line:
scanf(" %c \t",&repeat);
Remove the \t from the scanf and it should work properly. You don't want to scan for a tab character, just the 'Y' or 'y' character.
Also, your use of newlines is a bit unusual. Try putting newline characters at the end of your strings as opposed to the beginning.
Updated code:
#include <stdio.h>
#define MAX_SIZE 100
int main() {
int arr[MAX_SIZE];
int size, i, toSearch, found;
char repeat = ' ';
printf("Enter the size of an array\n");
scanf("%d", &size);
printf("Enter the array elements\n");
for (i = 0; i < size; i++)
scanf("%d", &arr[i]);
do{
printf("Enter element to search: \n");
scanf("%d", &toSearch);
found = 0;
for(i=0; i<size; i++) {
if(arr[i] == toSearch) {
found = 1;
break;
}
}
if(found == 1)
printf("%d is found at position %d\n", toSearch, i + 1);
else printf("%d is not found in the array\n", toSearch);
printf("Press Y to again Search Any Element in Array\nPress Any other Key to Exit the Program\n");
scanf(" %c",&repeat);
}
while(repeat == 'y' || repeat == 'Y' );
return 0;
}
Enclose the block of code you want to repeat in a while loop, something like
bool flag = false;
while(flag==true) {
//Code block
scanf("%c",&input)
if((input == 'y') || (input == 'Y')) {flag = true;}
else {flag = false;}
}
The first method that came to my mind :
#include <stdio.h>
#define MAX_SIZE 100
int main()
{
int arr[MAX_SIZE];
int size, i, toSearch, found;
char repeat;
printf("Enter the size of an array\n");
scanf("%d", &size);
printf("Enter the array elements\n");
for (i = 0; i < size; i++)
{
scanf("%d", &arr[i]);
}
do
{
printf("\nEnter element to search: ");
scanf("%d", &toSearch);
found = 0;
for (i = 0; i < size; i++)
{
if (arr[i] == toSearch)
{
found = 1;
break;
}
}
if (found == 1)
{
printf("\n%d is found at position %d", toSearch, i + 1);
}
else
{
printf("\n%d is not found in the array \n", toSearch);
}
printf("\n \n \nPress Y to again Search Any Element in Array\n \nPress Any other Key to Exit the Program\n\n");
repeat = getchar();
repeat = getchar();
if(repeat == 'y' || repeat == 'Y') {
continue;
}
else {
break;
}
} while (1);
return 0;
}

How to fix the error of get two string at the same time

I've got a task to input some information of some student and export it in the form of a report
#include <stdio.h>
#define MAX 1000
typedef struct
{
char id[6];
char name[80];
float grade;
char classassessment;
} exam;
void clear_buffer()
{
int ch;
while ((ch = getchar()) != '\n' && ch != EOF)
;
}
char assess(float a)
{
if (9 <= a && a <= 10)
return 'A';
else if (8 <= a && a < 9)
return 'B';
else if (6.5 <= a && a < 8)
return 'C';
else
return 'D';
}
int main()
{
char result[MAX];
exam student[MAX];
int n, i=0;
printf("The number of students: ");
scanf("%d", &n);
clear_buffer();
for (i = 0; i < n; i++)
{
printf("Enter student %d ID: ", i + 1);
scanf("%s", student[i].id);
clear_buffer();
printf("Enter this student name: ");
gets(student[i].name);
printf("Enter this student's grade: ");
scanf("%f", &student[i].grade);
clear_buffer();
result[i] = assess(student[i].grade);
}
for(i=0; i<n; i++)
{
printf("%d\t%s\t\t\t%s\t\t%c\n", i+1, student[i].id, student[i].name, result[i]);
}
return 0;
}
After compiling it, you can see that student[i].id has both ID and name while student[i].name still has names of the students that have just been inputted. I can not explain why it has this error.

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;
}

C getchar() hangman game

I was given a homework assignment which tasked us with creating a simple hangman game. Below is the code I have. I am currently trying to use if else with getchar() to ask the user to input a lowercase letter and see if it matches one of the letters in the word they are supposed to guess. From my very limited experience the code I have should work and when I step through the program it appears as if it should run properly, but when I actually run the program it seems to skip over the second getchar(). Anyone have any suggestions or help?
#include "stdio.h"
#include "math.h"
int main(void) {
int(a);
int(b);
float(x);
float(c);
float(e);
int word[4] = {116, 101, 115, 116};
int guess[4];
c == 0;
a == 0;
b == 0;
printf("Welcome to Hangman\n");
printf("Input a word--one lower case letter at a time\n");
printf("Enter Guess: ");
x = getchar();
if (x > 122) {
printf(" Error, character must be a lowercase letter");
} else
if (x < 97) {
printf(" Error, character must be a lowercase letter");
} else
if (x == 116) {
printf("t is correct\n");
printf("%d", word[0]);
printf(" _");
printf(" _");
printf(" %d ", word[3]);
e = getchar();
if (e == 101) {
printf("e is correct\n");
printf("%d", word[0]);
printf(" %d", word[1]);
printf(" _");
printf(" %d ", word[3]);
} else
if (e == 115) {
printf("s is correct\n");
printf("%d", word[0]);
printf(" _");
printf(" %d", word[2]);
printf(" %d", word[0]);
} else {
printf(" You guessed wrong");
}
} else
if (x == 101) {
printf("e is correct\n");
printf("_");
printf(" %d", word[1]);
printf(" _");
printf(" _ ");
} else
if (x == 115) {
printf("s is correct\n");
printf("_");
printf(" _");
printf(" %d", word[2]);
printf(" _ ");
} else {
printf(" You guessed wrong");
}
}
When you input a character that you want getchar to read, you end it with the Enter key right? That Enter key will also be put into the input buffer of stdin (which is what getchar reads from) as a newline, '\n'.
That means for each input you give, you actually input two characters.
You need to skip that newline. This can easily be done by just adding a second getchar after the first, like for example
x = getchar();
getchar(); // Read the newline from the Enter key
There is already a good answer, but to clarify the
problem a little bit more, here is a simple piece of code.
The function get_character will return the first entered character
and consume all following characters until the next '\n'.
It is not going to block if one character is EOF.
#include<stdio.h>
int get_character(void);
int main(void)
{
printf("character > ");
int c = get_character();
while(c != EOF && c != 'q')
{
printf("You entered %c\n", c);
printf("character > ");
c = get_character();
}
}
int get_character(void)
{
int c = getchar(), next_c;
if(c == EOF)
{
return EOF;
}
next_c = getchar(); // consume all \n
while(next_c != '\n' && next_c != EOF)
{
fprintf(stderr, "WARNING: consumed non-newline character: 0x%x\n", next_c);
next_c = getchar();
}
return c;
}
By the way: You are able to solve the hangman way faster:
int get_character(void);
#define MAX_TRIALS 3
#define WORD_LEN 4
int main(void)
{
char word[WORD_LEN + 1] = "test";
char correct[WORD_LEN] = {0, 0, 0, 0};
int trials = 0;
while(1)
{
if(trials > MAX_TRIALS)
{
printf("You failed. The word was: %s\n", word);
return 0;
}
printf("character > ");
int c = get_character();
if(c == EOF)
{
printf("bye\n");
return 0;
}
int i, this_char_correct = 0;
for(i = 0; i < WORD_LEN; i++)
{
if(c == word[i])
{
correct[i] = 1;
this_char_correct = 1;
}
if(correct[i])
{
printf("%c", word[i]);
}
else
{
printf("_");
}
}
if(!this_char_correct)
{
trials++;
}
int word_done = 1;
for(i = 0; i < WORD_LEN; i++)
{
word_done &= correct[i];
}
if(! word_done)
{
printf("\nYou have %d trials left\n", WORD_LEN - trials);
}
else
{
printf("\nYou got it.\n");
return 0;
}
}
}
This is just a piece of proof-of-concept code there might be way more elegant ways to solve this.

Reading in and recording a number in C

This is a homework problem. I have a C program that takes user input for a number of people's first names, last names, and ages. Right now it works and prints out the names to the console correctly, but it is not printing out the right ages, and I can't figure out what I'm doing wrong. Here's my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int choice;
int i = 0;
int x,k,l;
fputs("How many people would you like to add? ", stdout);
scanf(" %d", &choice);
fflush(stdout);
int ch;
while((ch = getchar()) != EOF && ch != '\n');
if (ch == EOF)
{
}
char firstName[choice][20];
char lastName[choice][20];
int age[choice][3];
char first[20];
char last[20];
int a[3];
for (x = 0; x < choice; x++)
{
for (l = 0; l < 3; l++)
{
age[x][l] = 0;
a[l] = 0;
}
}
while(i < choice)
{
printf("Enter the first name of person ");
printf(" %d", i);
printf(": ");
fgets(first, 20, stdin);
for (k = 0; k < 20; k++)
{
firstName[i][k] = first[k];
}
i++;
}
i = 0;
while(i < choice)
{
printf("Enter the last name of person ");
printf(" %d", i);
printf(": ");
fgets(last, 20, stdin);
for (k = 0; k < 20; k++)
{
lastName[i][k] = last[k];
}
i++;
}
i = 0;
while(i < choice)
{
fputs("Enter the age of person ", stdout);
printf(" %d", i);
printf(": ");
scanf(" %d", &a);
fflush(stdout);
for (l = 0; l < 3; l++)
{
age[i][l] = a[l];
}
i++;
}
int sh;
while((sh = getchar()) != EOF && sh != '\n');
if (sh == EOF)
{
}
for (x = 0; x < choice; x++)
{
printf("First name ");
printf(": ");
printf("%s ", firstName[x]);
printf("\n");
printf("Last name ");
printf(": ");
printf("%s ", lastName[x]);
printf("\n");
printf("Age ");
printf(": ");
printf("%d ", &age[x]);
printf("\n");
}
return 0;
}
If you copy/paste this code it will run, but the age outputted will be incorrect. Can anyone tell me why this is? Thank you!
scanf(" %d", &a);
That should be:
scanf(" %d", &a[0]);
And the printf should be printf("%d", age[x][0]);
You want to read into the first element of the array, not the entire array. You want to print out the first element of the array, not the address of the array.
A better solution would probably be not to make age an array of 3 at all. Each person only has one age. The changes would be:
int age[choice];
int a;
scanf(" %d", &a);
age[choice] = a;
printf("%d ", age[x]);

Resources