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;
}
Related
This is my code. The second printf and getchar does not pop up after hitting enter for the first scanf. I am unsure why the second printf and getchar are not working and what the fix would be.
#include <stdio.h>
int main()
{
int choice;
int i;
i = 0;
int n;
n = 1;
int p;
char message[1000];
printf("Would you like to (1) encrypt or (2) decrypt?: ");
scanf("%i\n", choice);
printf("\nType your message: ");
message[p] = getchar();
for (i = 1; (i < 1000 && message[p] != '\0');) {
message[p] = message[p] + n;
n + 1;
}
for (i = 0; (i < 1000 && message[p] != '\0');) {
message[p] = message[p] - n;
n + 1;
}
return 0;
}
Your encription method works for encription and decription. This compiles and takes in a string including spaces modifies it and prints it out.
#include <stdio.h>
int main() {
int choice;
char temp;
int i = 0;
int n = 1;
int p, b;
char message[1000];
char endmessage[1000];
printf("Would you like to (1) encrypt or (2) decrypt?: ");
scanf("%i", &choice); // change as per comment above
scanf("%c", &temp); /* temp statement to clear buffer otherwise a second character has to be typed before the next print statement is executed */
printf("Type your message: "); //prompt added for user clarity
scanf("%[^\n]", message); /* this scanf line allows for spaces in the message */
printf("\nmessage typed is: %s \n", message);
p = (sizeof( message) + 1); /* strings need to have an ending '\0'
message[p] = '\0';
if (choice == 1) {
for (i = 0; (i < 1000 && message[i] != '\0');) {
endmessage[i] = (message[i] + n);
i +=1;
}
b = (sizeof( endmessage)); // replace encripted \0 with '\0'
endmessage[b] = putchar('\0');
printf("\nYour message encripted is: %s\n\n", endmessage);
}
if (choice == 2) {
for (i = 0; (i < 1000 && message[i] != '\0');) {
endmessage[i] = message[i] - n;
i += 1;
}
b = (sizeof(endmessage) -2); // replace decripted \0 with '\0'
endmessage[b] = putchar('\0');
printf("\nYour message decripted is: %s\n\n", endmessage);
}
}
I have written a code which is supposed to crack a three digit numeric password. This code seems to work if the password is 888 or less than that. If the password is greater than 888, the code shows the following output:
Unable to crack password..
I'd like to know the reason behind this limitation and the solution to this problem. Thanks in advance.
#include <stdio.h>
#include <string.h>
int main()
{
char pswd[5];
char brute[4];
char crack[4];
printf("Program to crack a 3 digit numeric password\n ");
printf("Enter password: ");
scanf("%s", pswd);
int i, j, k;
int flag = 1;
for(i = 48; i < 57; ++i)
{
for(j = 48; j < 57; ++j)
{
for(k = 48; k < 57; ++k)
{
crack[0] = i;
crack[1] = j;
crack[2] = k;
crack[3] = 0;
if(strcmp(crack, pswd) == 0)
{
flag = 0;
break;
}
}
if(flag == 0) break;
}
if(flag == 0) break;
}
flag == 0 ? printf("Password cracked successfully.\
Your password is %s", crack) : printf("Unable to crack password..");
return 0;
}
The problem is that in your for-loops, the number 57 represents the character '9' but you added a strictly less than meaning you will not take the character '9', a simple fix would be to just add <='9' or <=57, so your code would look like:
#include <stdio.h>
#include <string.h>
int main()
{
char pswd[5];
char brute[4];
char crack[4];
printf("Program to crack a 3 digit numeric password\n ");
printf("Enter password: ");
scanf("%s", pswd);
int i, j, k;
int flag = 1;
for(i = '0'; i <= '9'; ++i)
{
for(j = '0'; j <= '9'; ++j)
{
for(k = '0'; k <= '9'; ++k)
{
crack[0] = i;
crack[1] = j;
crack[2] = k;
crack[3] = 0;
if(strcmp(crack, pswd) == 0)
{
flag = 0;
break;
}
}
if(flag == 0) break;
}
if(flag == 0) break;
}
flag == 0 ? printf("Password cracked successfully.\
Your password is %s", crack) : printf("Unable to crack password..");
return 0;
}
You could also change it to work for more than 3 digit numbers, my approach without arrays:
#include <stdio.h>
int main()
{
int pswd,brute = 0;
printf("Program to crack a positive password\n ");
do
{
printf("Enter password: ");
scanf("%d", &pswd);
} while(pswd<0);
while(brute != pswd)
brute++;
printf("The password is %d",brute);
getchar();
return 0;
}
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.
I have a school assignment to make a hangman game. The game works how I want it to except for one small glitch. If the user entered word is 4 letters or less, the hidden word is displayed with an extra "_\377" at the end. When the user entered word is 5 letters or more, then there is no glitch. I am hoping that someone would be kind enough to help me trouble shoot the problem. Thanks in advance!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int letterfinder(char string[], char a, int vari)
{
int length = strlen(string);
int i = vari;
int val = 0;
while( i <= length && val != 1)
{
if( string[i] == a)
{
val = 1;
}
i++;
}
if( val == 0)
{
return 100;
}
else
{
return i;
}
}
int main()
{
char inWord[] = "1111111111111111111111111111";
char outWord2[] = "1111111111111111111111111111";
char guess;
int gameover = 0;
int trys = 10;
int vari = 0;
printf("Please enter a word: ");
gets(inWord);
printf("%s\n", inWord);
printf(" \n");
printf(" \n");
printf(" \n");
printf(" \n");
printf(" \n");
printf(" \n");
int i2 = 0;
int j2 = 0;
int i3 = 0;
i2 = strcspn(inWord, outWord2);
char outWord[80];
while(i3 < i2)
{
outWord[i3] = '1';
i3++;
}
while(j2 < i2)
{
outWord[j2] = '-';
j2++;
}
puts(outWord);
while(gameover != 1 )
{
printf("What is your guess: ");
scanf("%s", &guess);
vari = 0;
if(letterfinder(inWord, guess, vari) == 100)
{
printf("Wrong!");
trys--;
printf("You have %d attempts left\n", trys);
if(trys == 0)
{
gameover = 1;
printf("You ran out of attempts. Game over\n");
}
}
else
{
outWord[(letterfinder(inWord, guess, vari) - 1)] = guess;
vari = (letterfinder(inWord, guess, vari));
while(letterfinder(inWord, guess, vari) != 100)
{
outWord[(letterfinder(inWord, guess, vari) - 1)] = guess;
vari = letterfinder(inWord, guess, vari);
}
puts(outWord);
}
int value = 0;
i3 = 0;
while( i3 <= i2)
{
if( outWord[i3] == '-')
{
value = 1;
}
i3++;
}
if(value != 1)
{
printf("Congratulations, you have guessed the word!\n");
gameover = 1;
}
}
return 0;
}
Your code has Undefined Behaviour. In the cases it "works" it is only by chance/luck. char guess; scanf("%s", &guess); That causes memory corruption as you are writing a string to a variable that can only hold a single char. Even a single letter guess will require two characters to store as all C strings are NUL terminated.
– kaylum
I have a problem thats giving me a huge ache.
This piece of code purpose is to fill up an array with integer values and at the same time defend against strings and etc....but it doesn't defend against duplicates, but tried I got to far as replacing the number with a new number for example
Enter 6 integers
1, 2, 2, 3, 4, 5
my code will let me replace that 2 at position 1 with another number. What I want it to do is not to repeat the same number again, for example please replace 2 at position 1. I dont want the user to enter 2 again... and I want to make it to double check the work the array if any repeating numbers exists thank you.
system("clear");
printf("\nEntering Winning Tickets....\n");
nanosleep((struct timespec[]){{1, 0}}, NULL);
system("clear");
char userInput[256];
char c;
int duplicationArray[6] = {-1, -1, -1, -1, -1, -1};
for (i = 0; i < 6; i++)
{
printf("\nPlease enter the %d winning ticket number!(#'s must be between 1-49): ", i+1);
fgets(userInput, 256, stdin);
if ((sscanf(userInput, "%d %c", &winningNumbers[i], &c) != 1 || (winningNumbers[i] <= 0) || winningNumbers[i] >= 50))
{
printf("\nInvalid Input.\n") ;
nanosleep((struct timespec[]){{0, 350000000}}, NULL);
system("clear");
i = i - 1;
}
}
for (i = 0; i < 6 - 1; ++i)
{
min = i;
for (j = i+1; j < 6; ++j)
{
if (winningNumbers[j] < winningNumbers[min])
min = j;
}
temp = winningNumbers[i];
winningNumbers[i] = winningNumbers[min];
winningNumbers[min] = temp;
}
for (i = 0; i < 6; i++)
{
if (winningNumbers[i] == winningNumbers[i+1])
{
duplicationArray[i] = i;
duplicationCounter++;
}
else
{
duplicationCounter--;
}
}
if (duplicationCounter > -6)
{
for (i = 0; i < 6; i++)
{
int j, min, temp;
min = i;
for (j = i+1; j < 6; ++j)
{
if (duplicationArray[j] > duplicationArray[min])
min = j;
}
temp = duplicationArray[i];
duplicationArray[i] = duplicationArray[min];
duplicationArray[min] = temp;
}
for (i = 0; i < 6; i++)
{
if (duplicationArray[i] == -1)
{
zeroCounter++;
}
}
int resize = (6 - zeroCounter)+1;
for (i = 0; i <= resize; i++)
{
if (duplicationArray[i] == -1)
{
i++;
}
else if (duplicationArray[i] != -1)
{
system("clear");
printf("\nDuplicated numbers has been dected in your array. ");
printf("\nPlease replace the number %d at postion %d with another number: ", winningNumbers[duplicationArray[i]], duplicationArray[i]);
fgets(userInput, 256, stdin);
if ((sscanf(userInput, "%d %c", &winningNumbers[duplicationArray[i]], &c) != 1 || (winningNumbers[i] <= 0) || winningNumbers[i] >= 50))
{
printf("\nInvalid Input.\n") ;
nanosleep((struct timespec[]){{0, 350000000}}, NULL);
system("clear");
i = i - 1;
}
}
}
duplicationCounter = 0;
for (i = 0; i < 6; i++)
{
if (winningNumbers[i] == winningNumbers[i+1])
{
duplicationArray[i] = i;
duplicationCounter++;
}
else
{
duplicationCounter--;
}
}
printf("%d, ", duplicationCounter);
}
#include <stdio.h>
#include <stdint.h>
#define DATA_SIZE 6
int main(void){
char userInput[256];
int inputNum, winningNumbers[DATA_SIZE];
uint64_t table = 0;
int i=0;
while(i<DATA_SIZE){
printf("\nPlease enter the %d winning ticket number!(#'s must be between 1-49): ", i+1);
fgets(userInput, sizeof(userInput), stdin);
if(sscanf(userInput, "%d", &inputNum) != 1 || inputNum <= 0 || inputNum >= 50)
continue;
uint64_t bit = 1 << inputNum;
if(table & bit)
continue;
table |= bit;
winningNumbers[i++] = inputNum;
}
for(i=0;i<DATA_SIZE;++i)
printf("%d ", winningNumbers[i]);
printf("\n");
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#define DATA_SIZE 6
int inputNumberWithRangeCheck(const char *msg, const char *errMsg, int rangeStart, int rangeEnd){
char inputLine[256];
int n;
for(;;){
printf("%s", msg);
fgets(inputLine, sizeof(inputLine), stdin);
if(sscanf(inputLine, "%d", &n) != 1 || n < rangeStart || n > rangeEnd)
fprintf(stderr, "%s", errMsg);
else
return n;
}
}
int inputNumber(void){
return inputNumberWithRangeCheck(
"\nPlease enter the winning ticket number!(#'s must be between 1-49): ",
"Invalid Input.\n",
1,49);
}
int *inputArray(int *array, size_t size){
int i;
for(i=0;i<size;++i){
printf("\nInput for No.%d\n", i+1);
array[i] = inputNumber();
}
return array;
}
int **duplicateCheck(int *array, size_t size){
int **check, count;
int i, j;
check = malloc(size*sizeof(int*));
if(!check){
perror("memory allocate\n");
exit(-1);
}
//There is no need to sort the case of a small amount of data
//(Cost of this loop because about bubble sort)
for(count=i=0;i<size -1;++i){
for(j=i+1;j<size;++j){
if(array[i] == array[j]){
check[count++] = &array[i];
break;
}
}
}
check[count] = NULL;
if(count)
return check;
else {
free(check);
return NULL;
}
}
int main(void){
int winningNumbers[DATA_SIZE];
int **duplication;
int i, j;
inputArray(winningNumbers, DATA_SIZE);
while(NULL!=(duplication = duplicateCheck(winningNumbers, DATA_SIZE))){
for(i=0;i<DATA_SIZE;++i){
if(duplication[i]){
printf("\nyour input numbers : ");
for(j=0;j<DATA_SIZE;++j)
printf("%d ", winningNumbers[j]);
fprintf(stderr, "\nThere is duplicate. Please re-enter.\n");
*duplication[i] = inputNumber();
} else
break;
}
free(duplication);
}
for(i=0;i<DATA_SIZE;++i)
printf("%d ", winningNumbers[i]);
printf("\n");
return 0;
}