I am in the process of creating hangman in C language, but there is one problem that I cannot quite grasp. When a user correctly guesses one of the letters that the word that is being guessed has, the program replaces all of previously guessed letters to the one user just put. What is the source of this problem?
#include<stdio.h>
#include <stdlib.h>
int main()
{
srand(time(NULL));
int x = 0, isCompleted, matchFound, numberOfTries = 7;
char letterGuess[1];
int randomIndex = rand()%14;
const char *wordArray[14];
const char *guessedWord[10];
const char *usedLetters[17];
for (int k = 0; k < 10; k++) {
guessedWord[k] = "_";
}
wordArray[0] = "butonierka";
wordArray[1] = "centyfolia";
wordArray[2] = "chiroplast";
wordArray[3] = "cmentarzyk";
wordArray[4] = "chrustniak";
wordArray[5] = "budowniczy";
wordArray[6] = "cholewkarz";
wordArray[7] = "cornflakes";
wordArray[8] = "brzydactwo";
wordArray[9] = "germanofil";
wordArray[10] = "lichtarzyk";
wordArray[11] = "lutowniczy";
wordArray[12] = "mikrocysta";
wordArray[13] = "tryskawiec";
const char *wordToGuess = wordArray[randomIndex];
for(int i = 0; i < 10; i++) {
printf(" %s ", guessedWord[i]);
}
printf("\n");
while(numberOfTries != 0 && isCompleted != 10) {
matchFound = 0;
isCompleted = 0;
printf("Please give a lowercase letter\n");
printf("Left tries: %d\n", numberOfTries);
scanf("%s", &letterGuess);
for (int z = 0; z < 17; z++) {
if (usedLetters[z] == letterGuess[0]) {
matchFound = 1;
}
}
if (letterGuess[0] >= 'a' && letterGuess[0] <= 'z' && matchFound == 0) {
usedLetters[x] = letterGuess[0];
x++;
for (int j = 0; j < 10; j++) {
if (letterGuess[0] == wordArray[randomIndex][j])
guessedWord[j] = letterGuess;
matchFound = 1;
}
}
if (matchFound == 0) {
numberOfTries--;
}
for(int z = 0; z < 10; z++) {
printf(" %s ", guessedWord[z]);
}
printf("\n");
} else {
if (matchFound == 1) {
printf("You've already given such letter!!\n");
} else {
printf("Wrong input, please try again!\n");
}
}
for (int k = 0; k < 10; k++) {
if (guessedWord[k] != "_") {
isCompleted++;
}
}
if (isCompleted == 10) {
printf("You have correctly guessed a word! Congrats!!\n");
}
printf("\n\n");
}
printf("The word was: %s\n", wordArray[randomIndex]);
printf("Game over!!\n");
}
The problem is that you're storing letterGuess, rather than individual characters. So each time letterGuess is updated with a new guess, all references to it change. Also, letterGuess is too short, leaving no room for the terminating null character.
The best solution is to make letterGuess a char (or an int), not an array, and to make guessedWord a char [] rather than a char *[]. There is no reason to use strings for single characters. That will solve the string-sharing problem.
Related
The error happens after the user enters the plaintext. I'm quite new to this language and programming itself. Help would be greatly appreciated. Since I am working in the cs50 codespace I cant use the debugger for some reason and cant see the code dump as one other question suggested I can solve the issue myself. Been at this for a few days and had to post a question now. Thanks.
bool no_repeat(string key, int l);
string cipher(string key, string input, int l);
int main(int argc, string argv[])
{
if (argc == 2)
{
string key = argv[1];
int l = strlen(key);
int ver = 0;
for (int i = 0; i < l; i++)
{
if (isalpha(key[i]))
{
ver++;
}
}
bool c = no_repeat(key, l);
if (strlen(argv[1]) == 0)
{
printf("Please enter an encryption key.\n");
return 1;
}
else if ((l != 26) || (ver != 26) || (c == false))
{
printf("Please input a correct encryption key.\n");
return 1;
}
}
else if (argc == 1)
{
printf("Please enter an encryption key.\n");
return 1;
}
string key = argv[1];
int l = strlen(key);
string input = get_string("plaintext:");
string cipherText = cipher(key, input, l);
printf("ciphertext: %s\n", cipherText);
return 0;
}
bool no_repeat(string key, int l)
{
for(int i = 0; i < l; i++)
{
for (int k = i+1; k < l; k++)
{
if (key[i] == key[k])
{
return false;
}
}
}
return true;
}
string cipher(string key, string input, int l)
{
string output = "";
string alphabets = "abcdefghijklmnopqrstuvwxyz";
for(int i = 0 ; i < l ; i++)
{
int isUpper = isupper(key[i]);
key[i] = tolower(key[i]);
for (int k = i ; k < l ; k++)
{
if (input[i] == alphabets[k])
{
output[i] = key[k];
}
else
{
output[i] = input[i];
}
}
if (isUpper != 0)
{
output[i] = toupper(output[i]);
}
}
return output;
}
string is probably a typedef char * string; and in that case you cannot modify string output = "";. Instead you want to use malloc() to allocate a string sufficiently large, i.e.:
string output = malloc(strlen(input) + 1);
if(!output) {
printf("malloc failed\n");
exit(1);
}
In cipher() you were also doing input[i] but i goes from 0 to strlen(key) so you will likely result in out of bound access. For me, cipher() was returning the input for ciphertext. Here is the fixed version (note, removed the argument l here and from caller as it's not needed):
string cipher(string key, string input) {
string output = malloc(strlen(input) + 1);
if(!output) {
printf("malloc failed\n");
exit(1);
}
const string alphabet = "abcdefghijklmnopqrstuvwxyz";
size_t j = 0;
for(size_t i = 0; i < strlen(input); i++, j++) {
string pos = strchr(alphabet, tolower(input[i]));
if(!pos) {
printf("letter %c not found in alphabet\n", input[i]);
exit(1);
}
output[j] = key[pos - alphabet];
}
output[j] = '\0';
return output;
}
and example execution:
~$ ./a.out abcdefghijklmnopqrtsuvwxzy # swap s and t
plaintext:test
ciphertext: sets
You don't have to store the alphabet, btw, as in ASCII pos - alphabet is the same value as tolower(input[i]) - 'a'.
I have a program in C which is supposed to merge 4 string arrays, sort this new list and then find a surname entered by the user. It works up to finding the surname; it says any surname entered is not in the list even if it is.
printf("Please enter the surname you wish to find\n");
gets(sntbf);
while (lf <= rg) {
p = lf + (rg - 1)/2;
int q = strcmp(list[p], sntbf);
if (q == 0) {
printf("This surname is located at elemnent %d \n", p);
z++;
} else if (q < 0) {
rg = p - 1;
} else if(q>0) {
lf = p + 1;
}
}
if (z==0) {
printf("This surname is not in the list \n");
}
Variables and constant values, only one of the original string arrays posted, the rest are identically formatted
#define SIZE 20
#define TOTAL 42
......
char list[TOTAL][SIZE];
char temp[SIZE];
char sntbf[SIZE];
//define miscellaneous integers to be used at various points of this program
int i = 0;
int j = 13;
int k = 27;
int l = 36;
int m = 0;
int n = 0;
int o = 0;
int lf = 0;
int rg = TOTAL-1;
int p;
int z = 0;
//define each class list as an array
char* a[13] = { "Harmon",
"Farrell",
"Ellison",
"Mcknight",
"Palmer",
"Caldwell",
"Mann",
"Townsend",
"Stuart",
"Hull",
"Pham",
"Singleton",
"Holden"
};
.......
Entire program:
//This is a program which will merge 4 lists of names, sort this new
list, and then find a student by searching for their surname
#include
#include
#define SIZE 20
#define TOTAL 42
int main() {
//define a 2d list array to hold the list of names and a temp array to be used when sorting, as well as a char array to hold the surname to be found
char list[TOTAL][SIZE];
char temp[SIZE];
char sntbf[SIZE];
//define miscellaneous integers to be used at various points of this program
int i = 0;
int j = 13;
int k = 27;
int l = 36;
int m = 0;
int n = 0;
int o = 0;
int lf = 0;
int rg = TOTAL-1;
int p;
int z = 0;
//define each class list as an array
char* a[13] = { "Harmon",
"Farrell",
"Ellison",
"Mcknight",
"Palmer",
"Caldwell",
"Mann",
"Townsend",
"Stuart",
"Hull",
"Pham",
"Singleton",
"Holden"
};
char* b[14] = { "Hudson",
"Harolds",
"Christian",
"Ware",
"Benjamin",
"Atkinson",
"Mcpherson",
"Michael",
"Perez",
"Austin",
"Graves",
"Hammond",
"Barry",
"Christensen"
};
char* c[9] = { "Adkins",
"Prince",
"Collins",
"Garrison",
"Skinner",
"Bean",
"Gentry",
"Chambers",
"Armstrong"
};
char* d[6] = { "Berg",
"Douglas",
"Novak",
"Turner",
"Love",
"Fowler",
};
//now merge all the lists into the list array
for(i=0; i<13; i++) {
strcpy(list[i], a[i]);
}
i=0; //reset i to use it again as a counter
for(i=0; i<14; i++) {
strcpy(list[j], b[i]);
j++;
}
i=0;
for(i=0; i<9; i++) {
strcpy(list[k], c[i]);
k++;
}
i=0;
for(i=0; i<6; i++) {
strcpy(list[l], d[i]);
l++;
}
for(m=0; m<TOTAL-1; m++) {
for(n=0; n<TOTAL; n++){
if(strcmp(list[m], list[n])<0) {
strcpy(temp, list[m]);
strcpy(list[m], list[n]);
strcpy(list[n], temp);
}
}
}
for(o=0; o<TOTAL; o++){
puts(list[o]);
}
printf("Please enter the surname you wish to find\n");
gets(sntbf);
while (lf <= rg) {
p = lf + (rg - 1)/2;
int q = strcmp(list[p], sntbf);
if(q = 0) {
printf("This surname is located at elemnent %d \n", p);
z ++;
}
else if(q < 0) {
rg = p - 1;
}
else if(q > 0) {
lf = p + 1;
}
}
if(z == 0) {
printf("This surname is not in the list \n");
}
return 0;
}
There are a number of problems with your program, but the first thing that I noticed is that when copying from list a which has 13 names, your for loop only copies 12:
for(i=0; i<12; i++) {
strcpy(list[i], a[i]);
}
either change "i<12" to "i <= 12" or "i < 13".
Ideally you would not use hard coded numbers at all, instead if you make the last element in each of the smaller lists NULL (0) you could use while loops and use a single int variable to represent both the next insertion point in the merged list and the total number of items in the list.
For example:
const char* a[] =
{"Harmon","Farrell","Ellison","Mcknight","Palmer","Caldwell",
"Mann","Townsend","Stuart","Hull","Pham","Singleton","Holden",0 };
const char* b[] = {
"Hudson","Harolds","Christian","Ware","Benjamin","Atkinson",
"Mcpherson","Michael","Perez","Austin","Graves","Hammond",
"Barry","Christensen",0 };
int sourceIndex = 0;
int destIndex = 0;
while ( a[sourceIndex] != 0 )
{
strcpy( list[destIndex], a[sourceIndex] );
sourceIndex++;
destIndex++;
}
sourceIndex = 0;
while ( b[sourceIndex] != 0 )
{
strcpy( list[destIndex], b[sourceIndex] );
sourceIndex++;
destIndex++;
}
and so on.
Also, your search is handling the bounds (lf & rg) backwards and it should look like this:
lf = 0;
rg = destIndex - 1;
while (lf<=rg) {
p = (rg + lf)/2;
int q = strcmp(list[p], sntbf);
if(q==0) {
printf("This surname is located at elemnent %d \n", p);
z++;
break;
}
else if(q<0) {
lf = p + 1;
}
else if(q>0) {
rg = p - 1;
}
}
if(z==0) {
printf("This surname is not in the list \n");
}
I am looking for a way to change words in string.
I want to change word to another word which have more symbols than first word.
First I count the symbols of the word which i want to change with another one,
than I count how many this word is in the text which is in my program as a char array(string) and now i want to change this word with the word which has more symbols.
There is the code:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
Start:
printf("This program can change word or symbols combanation in text\n\n");
char text[550] = "There was a grocery shop in a town. Plenty of mice lived in that grocery shop.\nFood was in plenty for them. hey also wasted the bread\nbiscuits and fruits of the shop.\nThe grocer got really worried. So, he thought I should buy a cat\nand let it stay at the grocery. Only then I can save my things.\nHe bought a nice, big fat cat and let him stay there. The cat had a nice\nime hunting the mice and killing them.\nThe mice could not move freely now. They were afraid that\n\n";
printf("%s\n", text);
int symbols_in_text = 0;
for (int f = 0;f < 550;f++)
{
if (text[f])
{
symbols_in_text++;
}
else
{
break;
}
}
printf("Text has %i symbols\n\n", symbols_in_text);
char b[15];
printf("Which word would you like to chenge in text above?\n(Maximum quantity of Symbols is 15)\nType word or some symbol(s)\n--->>");
cin >> b;
int word_symbols=0;
for (int a = 0;a < 15;a++)
{
if (b[a])
{
word_symbols++;
}
else
{
break;
}
}
printf("Word which you have entered has %i symbols\n", word_symbols);
int word_in_text = 0;
for (int i = 0; i < 550 - word_symbols; i++)
{
int found = 1;
for (int j = 0; j < word_symbols; j++)
{
if (b[j] != text[i + j])
{
found = 0;
break;
}
}
if (found && text[i + word_symbols]==' ')
{
word_in_text++;
}
}
printf("Founded %i %s as the word an is Not the some part of the other word\n", word_in_text,b);
if (word_in_text != 0)
{
char input_word[15];
printf("Enter the word which you want to insert for first entered word\nWarning:You have to enter the world which have %i symbols\n--->>", word_symbols);
cin >> input_word;
int in_word_symbols = 0;
for (int a = 0;a < 15;a++)
{
if (input_word[a])
{
in_word_symbols++;
}
else
{
break;
}
}
printf("The word which you have entered has %i symbols\n\n", in_word_symbols);
if (word_symbols == in_word_symbols)
{
for (int i = 0; i < 550 - word_symbols; i++)
{
int found = 1;
for (int j = 0; j < word_symbols; j++)
{
if (b[j] != text[i + j])
{
found = 0;
break;
}
}
if (found != 0 && text[i + word_symbols] == ' ')
{
for (int j = 0; j < in_word_symbols; j++)
{
text[i + j] = input_word[j];
}
}
}
printf("The result is--->>\n%s\n\n//////////////////////////////////////////END OF////////////////////////////////////////\n\n", text);
}
else if (in_word_symbols > word_symbols)
{
int text_char_index = 0;
step1:
for (int count = 0; count < 550 - word_symbols; count++)
{
text_char_index++;
int found = 1;
for (int j = 0; j < word_symbols; j++)
{
if (b[j] != text[count + j])
{
found = 0;
break;
}
if (found != 0 && text[count + word_symbols] == ' ')
{
count = text_char_index-1;
goto index_changing;
insert:
for (int c = 0; c < in_word_symbols; c++)
{
text[count + c] = input_word[c];
}
if (count > 500)
{
goto printing_result;
}
else
{
continue;
}
}
}
}
index_changing:
for (int l = 466; l > text_char_index + word_symbols; --l)
{
text[l] = text[l + 1];
}
goto insert;
printing_result:
printf("The result is--->>\n%s\n\n//////////////////////////////////////////END OF////////////////////////////////////////\n\n", text);
}
}
goto Start;
return 0;
}
If I enter the word was ( - it is word which i want to change in text) and than I enter the word detected (which has more symbols than first entered word - an it is the word which i want to insert in the text in return "was")
Console output is: There detected
And I can't use in this code method or something like that, I can only use if() and for loop.
Can anyone help me to understand how to do it?
First let's get the ground rules straight -- you are not allowed to use string functions/methods in this exercise, you have to write the code out explicity using primarily if statements and loops.
Rather than create a whole separate block of code to deal with the replacement word being larger than the original, just deal with it as part of the original replacement code -- as well as deal with the possibility that the replacement word is smaller. Both require shifting the original text one way or the other based on the difference between the original word and the replacement.
Here is a rework of your code that does the above and makes a number of style changes and bug fixes. It also makes it a pure 'C' program:
#include <stdio.h>
#include <stdbool.h>
int main()
{
printf("This program can change word or character combinations in text.\n\n");
char text[1024] =
"There was a grocery shop in a town. Plenty of mice lived in that grocery shop.\n"
"Food was in plenty for them. They also wasted the bread, biscuits and fruits\n"
"of the shop. The grocer got really worried. So, he thought I should buy a cat\n"
"and let it stay at the grocery. Only then I can save my things. He bought a\n"
"nice, big fat cat and let him stay there. The cat had a nice time hunting mice\n"
"and killing them. The mice could not move freely now. They were afraid that\n";
while (true) {
printf("%s\n", text);
int characters_in_text = 0;
for (int f = 0; text[f] != '\0'; f++) // not allowed to use strlen()
{
characters_in_text++;
}
printf("Text has %i characters.\n\n", characters_in_text);
char word[17];
printf("Which word would you like to change in text above?\n");
printf("(Maximum quantity of characters is %d)\n", (int) sizeof(word) - 2);
printf("Type word or some character(s)\n");
printf("--->> ");
(void) fgets(word, sizeof(word), stdin);
int a, word_characters = 0;
for (a = 0; word[a] != '\n'; a++)
{
word_characters++;
}
word[a] = '\0';
if (word_characters == 0)
{
break; // exit program
}
printf("Word which you have entered has %i characters.\n", word_characters);
int words_in_text = 0;
for (int i = 0; i < characters_in_text - word_characters; i++)
{
bool found = true;
for (int j = 0; j < word_characters; j++)
{
if (word[j] != text[i + j])
{
found = false;
break;
}
}
if (found)
{
char next_letter = text[i + word_characters];
if (next_letter == ' ' || next_letter == '.' || next_letter == ',' || next_letter == '\n' || next_letter == '\0')
{
words_in_text++;
}
}
}
printf("Found %i instance(s) of %s that are not part of another word.\n", words_in_text, word);
char replacement_word[17];
printf("Enter the word which you want to insert for first entered word.\n");
printf("(Maximum quantity of characters is %d)\n", (int) sizeof(replacement_word) - 2);
printf("Type word or some character(s)\n");
printf("--->> ");
(void) fgets(replacement_word, sizeof(replacement_word), stdin);
int replacement_word_characters = 0;
for (a = 0; replacement_word[a] != '\n'; a++)
{
replacement_word_characters++;
}
replacement_word[a] = '\0';
printf("The word which you have entered has %i characters.\n\n", replacement_word_characters);
int text_shift = replacement_word_characters - word_characters;
for (int i = 0; i < characters_in_text - word_characters; i++)
{
bool found = true;
for (int j = 0; j < word_characters; j++)
{
if (word[j] != text[i + j])
{
found = false;
break;
}
}
if (found)
{
char next_letter = text[i + word_characters];
if (next_letter == ' ' || next_letter == '.' || next_letter == ',' || next_letter == '\n' || next_letter == '\0')
{
if (text_shift > 0)
{
for (int k = characters_in_text; k > i + word_characters - 1; k--)
{
text[k + text_shift] = text[k];
}
}
else if (text_shift < 0)
{
for (int k = i + word_characters; k < characters_in_text + 1; k++)
{
text[k + text_shift] = text[k];
}
}
characters_in_text += text_shift;
for (int j = 0; j < replacement_word_characters; j++)
{
text[i + j] = replacement_word[j];
}
}
}
}
}
return 0;
}
You can see how complicated this code gets without library functions -- testing for the possible punctuation that follows a word would be a lot easier with functions like ispunct() in ctype.h
You also computed a number of useful values in your original code but failed to use them appropriately later on in the code.
Yet to do: you've a lot of error checks to add to this code -- what if the replacement makes the text larger than the array that contains it? You check that a word isn't contained in another by testing the character after the word but fail to test the character before the work, e.g. 'other' vs. 'another'.
I have tried to create an implementation of a vigenere cipher, but have come across a hurde in the form of the program not working properly when given spaces in the input. (Assume keyword bacon)
With Spaces
Input
Meet me
Correct Output
Negh zf
Actual Output
Negh Ne
Without Spaces
Input
Meetme
Ouput
Neghzf
So clearly the program is working for strings without the spaces. Anywhere here is the code and thanks in advance for help.
#include <string.h>
#include <stdio.h>
#include <ctype.h>
char encrypt(int key, char a);
int hash(char a);
int main(int argc, string argv[])
{
if (argc != 2)
{
printf("You need a keyword!");
return 1;
}
string keyword = argv[1];
for (int j = 0; j != strlen(keyword); ++j)
{
if (!isalpha(keyword[j]))
{
printf ("The keyword needs to be all words!");
return 1;
}
}
string text = GetString();
for (int i = 0, j = 0; i != strlen(text); ++i, ++j)
{
if (j == strlen(keyword))
{
j = 0;
}
int key = 0;
if (isupper(keyword[j]))
{
key = keyword[j] - 'A';
text[i] = encrypt(key, text[i]);
}
else if (islower(keyword[j]))
{
key = keyword[j] - 'a';
text[i] = encrypt(key, text[i]);
}
else if (isspace(text[i]))
{
j = j - 1;
}
}
printf ("%s\n", text);
}
char encrypt(int key, char a)
{
if (isalpha(a))
{
int total = (int) a + key;
if (isupper(a))
{
while (total > 90)
{
total = total - 26;
}
}
else if (islower(a))
{
while (total > 122)
{
total = total - 26;
}
}
return (char) total;
}
else
{
return a;
}
}
the problem is inside your for loop. Try to correct it in the following way (you will understand easily the mistake):
for (int i = 0, j = 0; i != strlen(text); ++i, ++j)
{
if (j == strlen(keyword))
{
j = 0;
}
// the following check mmust be done here
if (isspace(text[i])) {
j = j - 1;
}
int key = 0;
if (isupper(keyword[j]))
{
key = keyword[j] - 'A';
text[i] = encrypt(key, text[i]);
}
else if (islower(keyword[j]))
{
key = keyword[j] - 'a';
text[i] = encrypt(key, text[i]);
}
}
It looks like you are reading your words from command line arguments; however, command line arguments are typically separated by whitespace. Your program doesn't know that those spaces are supposed to be part of the input.
You need to change the way you are reading input.
So I may be attacking this the wrong way; I was learning a bit of Javascript and wrote a program that will find a string contained in another string and store the matches in an array (sorry if that didn't make too much sense, seeing my C program should help). I tried to translate my program to C, but it doesn't work; I think my issue is data types:
int main () {
char text[58];
strcpy(text, "I am James, James the Great, a pretty cool guy named James");
char store[16];
char name[6] = "James";
for (int i = 0; i <= 16; i++) {
if (text[i] == 'J') {
for (int k = i; k < i + 6; k++) {
store[k] = text[i];
}
}
}
int a = sizeof(store) / sizeof(store[0]);
for (int b = 0; b < a; b++) {
/* This should print out the values stored in the store array */
printf("%d", store[b]);
}
return 0;
}
My expected result would be something like:
JamesJamesJames
Instead I get:
10000747474747474-6374747474
So I'm assuming it's doing exactly what I told it to do, just not storing the letters into the array as letters, a bit confusing. Is there a better way to do this?
This is the javascript code I was trying to translate:
var text = "I am James, James the Great, a pretty cool guy named James";
var myName = "James";
var hits =[];
for (i = 0; i < text.length; i++) {
if (text[i] === "J") {
for (var j = i; j < i + myName.length ; j++) {
hits.push(text[j]);
}
}
}
if (hits.length === 0) {
console.log("Your name wasn't found!");
} else{
console.log(hits);
}
You are going to break store[] with this line
for (int k = i; k < i + 6; k++) {
because you are writing to the same index as you found the text in text[]. You also loop one too many times (6)
int ind = 0;
for (int k = 0; k < 5; k++) {
store[ind++] = text[i+k];
}
Then your next statement doesn't tell you anything about the data you collected
int a = sizeof(store) / sizeof(store[0]);
Just remove it, and print ind characters from store[].
You made following mistakes.
for (int i = 0; i <= 16; i++)
You iterate by '16' but this isn't proper length of text.
for (int k = i; k < i + 6; k++)
So you iterate by "i, i+1, i+2, i+3, i+4, i+5, i+6" here is 7 chars, "James" have 6.
store[k] = text[i];
You aren't changing "i" value so text[i] always return 'J'. It's better to use savePoistion variable so do I in the following code.
int a = sizeof(store) / sizeof(store[0]);
for (int b = 0; b < a; b++) {
/* This should print out the values stored in the store array */
printf("%d", store[b]);
}
I have no idea what are you trying to do here. It's really unnecessary.
printf("%d", store[b]);
"%d" means that you are printing integers so don't be surprised that your output was numbers. Just simply printf("%s\n", store);
This should look like this
int main () {
char text[58];
strcpy(text, "I am James, James the Great, a pretty cool guy named James");
char store[20];
int len = strlen(text);
int savePosition = 0;
int i, k;
for (i = 0; i < len; i++) {
if (text[i] == 'J') {
for ( k = i; k < i + 5; k++) {
store[savePosition] = text[k];
++savePosition;
}
}
}
store[savePosition] = '\0';
printf("%s\n", store);
return 0;
}
int main (void) {
char text[] = "I am James, James the Great, a pretty cool guy named James";
char name[] = "James";
char store[16] = {0};
int store_index = 0;
for (int i = 0; i < strlen(text); i++) {
if (text[i] == 'J') {
for (int k = i; k < i + strlen(name); k++) {
store[store_index++] = text[k];
}
}
}
if(strlen(store)==0) {
printf("Your name wasn't found!\n");
} else {
printf("%s\n", store);
}
return 0;
}
rewrite version.
int main (void) {
char text[] = "I am James, James the Great, a pretty cool guy named James";
char name[] = "James";
char store[sizeof(text)];
char *p = strstr(text, name);
if(p == NULL) {
printf("Your name wasn't found!\n");
} else {
int len = strlen(name);
int index = 0;
do {
memcpy(store + index, name, len);
index += len;
p = strstr(p + len, name);
} while(p != NULL);
store[index] = 0;
printf("%s\n", store);
}
return 0;
}