Hi guys I wrote a better and improved hangman game that accepts lowercase input and uppercase input.
The only problem that I have is that for example if the String looks like this "tnt" it prints out every character big in the console. I am trying to make it print out the exact same string.
So if I input big 'T' then it should accept it and output small 't'.
Could someone help me?
Thank you in advance.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <ctype.h>
#define MAX_WORD 100
int get_word(char *word, int size) {
fgets(word, size, stdin);
int len = strlen(word);
if (len && word[len - 1] == '\n')
word[--len] = '\0';
for (int i = 0; i < len; ++i)
if (isalpha(word[i]))
word[i] = toupper(word[i]);
else
return -1;
return len;
}
void create_output(char *output, int len) {
for (int i = 0; i < len; ++i)
output[i] = '_';
output[len] = '\0';
}
void print_output(const char *output, const char *alpha, int tries) {
printf("(%d) ", tries);
for (int i = 0; output[i]; ++i)
printf("%c ", output[i]);
printf(" %s\n", alpha);
}
bool play_game(const char *word, int len) {
char alpha[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char output[MAX_WORD];
create_output(output, len);
int tries = 0, guessed = 0;
while (tries < len && guessed < len) { // using word length for number of tries (?!)
print_output(output, alpha, tries);
printf("Guess: ");
char guess;
scanf(" %c", &guess);
guess = toupper(guess);
if (alpha[guess - 'A'] != ' ') {
for (int i = 0; i < len; ++i)
if (word[i] == guess && output[i] == '_') {
output[i] = word[i];
++guessed;
}
alpha[guess - 'A'] = ' ';
++tries;
}
}
print_output(output, alpha, tries);
return guessed == len;
}
int main() {
printf("Enter word to guess: ");
char word[MAX_WORD];
int len = get_word(word, sizeof word);
if (len == -1) {
printf("The word cannot contain spaces.\n");
return EXIT_FAILURE;
}
if (play_game(word, len))
printf("You win!\n");
else
printf("You lose.\nThe word was %s.\n", word);
return 0;
}
Related
I am trying to reverse the order of words in a string, but my output is a bunch of junk that makes no sense. I don't know what is the problem, maybe the loops are broken.
Appreciate it if someone can explain what is wrong with my code below. I still new to C programming and this kind of problem is kind of frustrating.
#include<stdio.h>
int main()
{
//declare variable
char string[100], rev_string[100];
//declare number of loop
int i, j, len;
printf("enter the string: ");
scanf("%s",string);
//finding the length
len = strlen(string);
printf("strings length: %d\n", len);
for (i = len - 1; i >= 0; i--)
for (j = 0; j < len - 1; j++)
rev_string[j] = string[i];
rev_string[j] = '\0';
if (strcmp(string, rev_string) == 0)
printf("rev_string: %s is a palindrome", rev_string);
else
printf("rev_string : %s is not a palindrome words",rev_string);
return(0);
}
Your title is a bit confusing because your code seems to be a palindrome check and it should reverse the string, not the order of the words.
To reverse the string you can simply do:
for (i = 0; i < len; i++)
rev_string[i] = string[len - i - 1];
This code can help you :
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>
#define NCHARS 256 /* constant to count array size, covers ASCII + extended ASCII */
int ispalindrom (const char *s1, const char *s2)
{
int count[NCHARS] = {0}; /* counting array, covers all extended ASCII */
for (; *s1; s1++) /* loop over chars in string 1 */
if (!isspace(*s1)) /* if not whitespace */
count[(int)*s1]++; /* add 1 to index corresponding to char */
for (; *s2; s2++) /* loop over chars in string 2 */
if (!isspace(*s2)) /* if not whitespace */
count[(int)*s2]--; /* subtract 1 from index corresponding to char */
for (int i = 0; i < NCHARS; i++) /* loop over counting array */
if (count[i]) /* if any index non-zero, not anagram */
return 0;
return 1; /* all chars used same number of times -> anagram */
}
void main()
{
int i, j = 0, k = 0, x, len;
char str[100], str1[10][20], temp;
char str2[100];
printf("enter the string :");
scanf("%[^\n]s", str);
for (int i = 0;str[i] != '\0'; i++)
{
str2[i]=str[i];
}
/* reads into 2d character array */
for (int i = 0;str[i] != '\0'; i++)
{
if (str[i] == ' ')
{
str1[k][j]='\0';
k++;
j=0;
}
else
{
str1[k][j]=str[i];
j++;
}
}
str1[k][j] = '\0';
/* reverses each word of a given string */
for (int i = 0;i <= k;i++)
{
len = strlen(str1[i]);
for (int j = 0, x = len - 1;j < x;j++,x--)
{
temp = str1[i][j];
str1[i][j] = str1[i][x];
str1[i][x] = temp;
}
}
for (int i = 0;i <= k;i++)
{
printf("%s ", str1[i]);
}
printf("\n\n");
if (ispalindrom(str1, str2)==0)
{
printf("The word is Palindrom !\n");
}
else
{
printf("The word is not Palindrom !\n");
}
}
#include <stdbool.h>
#include <stdio.h>
bool ispalindrom(char *str,int k)
{
for(int i=0;i<k;i++)
{
if(str[i]!=str[k-i-1])
{
return false;
}
}
return true;
}
int main()
{
char string[100];
printf("enter the string: ");
scanf("%s",string);
if (ispalindrom(string,strlen(string)))
{
printf("\nrev_string: %s is a palindrome\n", string);
}
else
{
printf("\nrev_string : %s is not a palindrome words\n",string);
}
}
you can use a loop first to reverse the string first and then use strcomp()
#include<stdio.h>
#include <string.h>
int main()
{
//declare variable
char string[100], rev_string[100];
//declare number of loop
int i, j =0 , len;
printf("enter the string: ");
scanf("%s",string);
//finding the length
len = strlen(string);
printf("strings length: %d\n", len);
for (i = len - 1;i >= 0;i--){
rev_string[j] = string[i];
j++;
}
//check the rev_string if you want
/*for (i = 0; i < len; i++){
printf("%c\n",rev_string[i]);
}*/
if(strcmp(rev_string,string) == 0){
printf("Is Palindrome\n");
return(0);
}else{
printf("Is not Palindrome\n");
return(1);
}
}
I have program to remove the similar words from string but this program only removing at once word not a repeating words.
For example input:
sabunkerasmaskera kera
and should an output:
sabunmas
This my code:
#include <stdio.h>
#include <string.h>
void remove(char x[100], char y[100][100], char words[100]) {
int i = 0, j = 0, k = 0;
for (i = 0; x[i] != '\0'; i++) {
if (x[i] == ' ') {
y[k][j] = '\0';
k++;
j = 0;
} else {
y[k][j] = x[i];
j++;
}
}
y[k][j] = '\0';
j = 0;
for (i = 0; i < k + 1; i++) {
if (strcmp(y[i], kata) == 0) {
y[i][j] = '\0';
}
}
j = 0;
for (i = 0; i < k + 1; i++) {
if (y[i][j] == '\0')
continue;
else
printf("%s ", y[i]);
}
printf ("\n");
}
int main() {
char x[100], y[100][100], kata[100];
printf ("Enter word:\n");
gets(x);
printf("Enter word to remove:\n");
gets(words);
remove(x, y, words);
return 0;
}
My program output its:
sabunkerasmaskerara
and that should not be the case. Maybe I need your opinion to fixed this program and also I need help to make it better.
Your solution does not work because it uses strcmp to compare the string portions, which only works if the substring is at the end of the string, as this makes it null-terminated.
You should instead use strstr to locate the matches and use memmove to shift the string contents.
There are other issues in your code:
do not use gets()
y is unnecessary for this task.
words is not defined
Here is a modified version:
#include <stdio.h>
#include <string.h>
char *remove_all(char *str, const char *word) {
size_t len = strlen(word);
if (len != 0) {
char *p = str;
while ((p = strstr(p, word)) != NULL) {
memmove(p, p + len, strlen(p + len) + 1);
}
}
return str;
}
int main() {
char str[100], word[100];
printf ("Enter string:\n");
if (!fgets(str, sizeof str, stdin))
return 1;
printf("Enter word to remove:\n");
if (!fgets(word, sizeof word, stdin))
return 1;
word[strcspn(word, "\n")] = '\0'; // strip the trailing newline if any
remove_all(str, word);
fputs(str, stdout);
return 0;
}
I need to write code that reads a string of characters such as jasf#fjaf#afsj to a single dimension string and then ask for a separation character (eg: #) so it will get an output in two dimensions and for every line, it will be the words between the separation character like:
jasf
fjaf
afsj
I tried:
#include <stdio.h>
#include <string.h>
void main {
int s, k, b;
printf("please enter a long string\n");
gets(longstring);
s = strlen(longstring);
printf("please choose seperationg charcter\n");
scanf("%c", &ch);
if ((ch < 'A') || ((ch > 'Z') && (ch < 'a')) || (ch > 'z')) {
for (k = 0; k < s; k++) {
for (b = 0; longstring[k] == ch; ++b) {
strcpy(mat[b], longstring);
}
}
puts(mat[b]);
}
Your code is incomplete: the function definition for main lacks its argument list, which is not optional in C, longstring is not defined, etc.
Futhermore, your method is too complicated: you do not need to test for letters if the goal is just to output one line for each part of the string between separators.
Here is a simple solution:
#include <stdio.h>
#include <string.h>
int main() {
char longstring[256];
int i, len;
char sep;
printf("please enter a long string\n");
if (fgets(longstring, sizeof longstring, stdin)) {
len = strlen(longstring);
printf("please choose a separationg character: ");
if (scanf("%c", &sep) != 1)
return 1;
for (i = 0; i < len; i++) {
if (longstring[i] == sep)
putchar('\n');
else
putchar(longstring[i]);
}
}
return 0;
}
since your code is not complete , let me add what is missing to achieve the task :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
char** str_split(char* a_str, const char a_delim)
{
char** result = 0;
size_t count = 0;
char* tmp = a_str;
char* last_comma = 0;
char delim[2];
delim[0] = a_delim;
delim[1] = 0;
/* Count how many elements will be extracted. */
while (*tmp)
{
if (a_delim == *tmp)
{
count++;
last_comma = tmp;
}
tmp++;
}
/* Add space for trailing token. */
count += last_comma < (a_str + strlen(a_str) - 1);
/* Add space for terminating null string so caller
knows where the list of returned strings ends. */
count++;
result = (char**) malloc(sizeof(char*) * count);
if (result)
{
size_t idx = 0;
char* token = strtok(a_str, delim);
while (token)
{
assert(idx < count);
*(result + idx++) = strdup(token);
token = strtok(0, delim);
}
assert(idx == count - 1);
*(result + idx) = 0;
}
return result;
}
int main()
{
char longstring[1024];
char** tokens;
char ch;
unsigned long s;
printf("please enter a long string\n");
gets(longstring);
s = strlen(longstring);
printf("please choose seperationg charcter\n");
scanf("%c", &ch);
if ((ch<'A') || ((ch>'Z') && (ch<'a')) || (ch>'z'))
{
tokens = str_split(longstring, ch);
if (tokens)
{
int i;
for (i = 0; *(tokens + i); i++)
{
printf("%s\n", *(tokens + i));
free(*(tokens + i));
}
printf("\n");
free(tokens);
}
}
return 0;
}
I have problem with my alignement. This time I want my program to return words that ends and starts with the same letter. I've wrote something like this, but it seems to return random words.
#include <stdio.h>
#include <string.h>
void main()
{
char str[100];
int i, t, j, len;
printf("Enter a string : ");
scanf("%[^\n]s", str);
len = strlen(str);
str[len] = ' ';
for (t = 0, i = 0; i < strlen(str); i++)
{
if ((str[i] == ' ') && (str[i - 1] == str[0]))
{
for (j = t; j < i; j++)
printf("%c", str[j]);
t = i + 1;
printf("\n");
}
else
{
if (str[i] == ' ')
{
t = i + 1;
}
}
}
}
You can use strtok to split the strings from stdin, then apply a letter checker on each parsed word one at a time.
Something like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAXCHAR 100
int is_start_end(char *word);
void exit_if_null(void *ptr, const char *msg);
int
main(void) {
char str[MAXCHAR];
char *word;
char **all_words;
int words_size = 1, word_count = 0;
int i, found;
all_words = malloc(words_size * sizeof(*all_words));
exit_if_null(all_words, "initial Allocation");
printf("Enter words(enter empty line to terminate):\n");
while (fgets(str, MAXCHAR, stdin) != NULL && strlen(str) != 1) {
word = strtok(str, " \n");
while (word !=NULL) {
if (words_size == word_count) {
words_size *= 2;
all_words = realloc(all_words, words_size * sizeof(*all_words));
exit_if_null(all_words, "Reallocation");
}
all_words[word_count] = malloc(strlen(word)+1);
exit_if_null(all_words[word_count], "Initial Allocation");
strcpy(all_words[word_count], word);
word_count++;
word = strtok(NULL, " \n");
}
}
printf("Words that have equal first and last letters:\n");
found = 0;
for (i = 0; i < word_count; i++) {
if (is_start_end(all_words[i])) {
found = 1;
printf("%s\n", all_words[i]);
}
free(all_words[i]);
all_words[i] = NULL;
}
if (found == 0) {
printf("None Found\n");
}
free(all_words);
all_words = NULL;
return 0;
}
int
is_start_end(char *word) {
int len;
len = strlen(word);
if ((len == 1) || (tolower(word[0]) == tolower(word[len-1]))) {
return 1;
}
return 0;
}
void
exit_if_null(void *ptr, const char *msg) {
if (!ptr) {
printf("Unexpected null pointer: %s\n", msg);
exit(EXIT_FAILURE);
}
}
This line removes the null terminator of the string:
len = strlen(str);
str[len] = ' ';
thus the string no longer exists, what is left is just an ordinary array of characters.
The next call to strlen, in the body of the for loop, will cause undefined behavior.
I need to write a function that will count words in a string. For the
purpose of this assignment, a "word" is defined to be a sequence
of non-null, non-whitespace characters, separated from other words by
whitespace.
This is what I have so far:
int words(const char sentence[ ]);
int i, length=0, count=0, last=0;
length= strlen(sentence);
for (i=0, i<length, i++)
if (sentence[i] != ' ')
if (last=0)
count++;
else
last=1;
else
last=0;
return count;
I am not sure if it works or not because I can't test it until my whole program is finished and I am not sure it will work, is there a better way of writing this function?
You needed
int words(const char sentence[])
{
}
(note braces).
For loops go with ; instead of ,.
Without any disclaimer, here's what I'd have written:
See it live http://ideone.com/uNgPL
#include <string.h>
#include <stdio.h>
int words(const char sentence[ ])
{
int counted = 0; // result
// state:
const char* it = sentence;
int inword = 0;
do switch(*it) {
case '\0':
case ' ': case '\t': case '\n': case '\r': // TODO others?
if (inword) { inword = 0; counted++; }
break;
default: inword = 1;
} while(*it++);
return counted;
}
int main(int argc, const char *argv[])
{
printf("%d\n", words(""));
printf("%d\n", words("\t"));
printf("%d\n", words(" a castle "));
printf("%d\n", words("my world is a castle"));
}
See the following example, you can follow the approach : count the whitespace between words .
int words(const char *sentence)
{
int count=0,i,len;
char lastC;
len=strlen(sentence);
if(len > 0)
{
lastC = sentence[0];
}
for(i=0; i<=len; i++)
{
if((sentence[i]==' ' || sentence[i]=='\0') && lastC != ' ')
{
count++;
}
lastC = sentence[i];
}
return count;
}
To test :
int main()
{
char str[30] = "a posse ad esse";
printf("Words = %i\n", words(str));
}
Output :
Words = 4
#include <ctype.h> // isspace()
int
nwords(const char *s) {
if (!s) return -1;
int n = 0;
int inword = 0;
for ( ; *s; ++s) {
if (!isspace(*s)) {
if (inword == 0) { // begin word
inword = 1;
++n;
}
}
else if (inword) { // end word
inword = 0;
}
}
return n;
}
bool isWhiteSpace( char c )
{
if( c == ' ' || c == '\t' || c == '\n' )
return true;
return false;
}
int wordCount( char *string )
{
char *s = string;
bool inWord = false;
int i = 0;
while( *s )
{
if( isWhiteSpace(*s))
{
inWord = false;
while( isWhiteSpace(*s) )
s++;
}
else
{
if( !inWord )
{
inWord = true;
i++;
}
s++;
}
}
return i;
}
Here is one of the solutions. It counts words with multiple spaces or just space or space followed by the word.
#include <stdio.h>
int main()
{
char str[80];
int i, w = 0;
printf("Enter a string: ");
scanf("%[^\n]",str);
for (i = 0; str[i] != '\0'; i++)
{
if((str[i]!=' ' && str[i+1]==' ')||(str[i+1]=='\0' && str[i]!=' '))
{
w++;
}
}
printf("The number of words = %d", w );
return 0;
}
I know this is an old thread, but perhaps someone needs a simple solution, just checks for blank space in ascii and compares current char to that while also makign sure first char is not a space, cheers!
int count_words(string text){
int counter = 1;
int len = strlen(text);
for(int i = 0; i < len; i++){
if(text[i] == 32 && i != 0) {
counter++;
}
}
return counter;}
Here is another solution:
#include <string.h>
int words(const char *s)
{
const char *sep = " \t\n\r\v\f";
int word = 0;
size_t len;
s += strspn(s, sep);
while ((len = strcspn(s, sep)) > 0) {
++word;
s += len;
s += strspn(s, sep);
}
return word;
}
#include<stdio.h>
int main()
{
char str[50];
int i, count=1;
printf("Enter a string:\n");
gets(str);
for (i=0; str[i]!='\0'; i++)
{
if(str[i]==' ')
{
count++;
}
}
printf("%i\n",count);
}
#include<stdio.h>
#include<string.h>
int getN(char *);
int main(){
char str[999];
printf("Enter Sentence: "); gets(str);
printf("there are %d words", getN(str));
}
int getN(char *str){
int i = 0, len, count= 0;
len = strlen(str);
if(str[i] >= 'A' && str[i] <= 'z')
count ++;
for (i = 1; i<len; i++)
if((str[i]==' ' || str[i]=='\t' || str[i]=='\n')&& str[i+1] >= 'A' && str[i+1] <= 'z')
count++;
return count;
}
#include <stdio.h>
int wordcount (char *string){
int n = 0;
char *p = string ;
int flag = 0 ;
while(isspace(*p)) p++;
while(*p){
if(!isspace(*p)){
if(flag == 0){
flag = 1 ;
n++;
}
}
else flag = 0;
p++;
}
return n ;
}
int main(int argc, char **argv){
printf("%d\n" , wordcount(" hello world\nNo matter how many newline and spaces"));
return 1 ;
}
I found the posted question after finishing my function for a C class I'm taking. I saw some good ideas from code people have posted above. Here's what I had come up with for an answer. It certainly is not as concise as other's, but it does work. Maybe this will help someone in the future.
My function receives an array of chars in. I then set a pointer to the array to speed up the function if it was scaled up. Next I found the length of the string to loop over. I then use the length of the string as the max for the 'for' loop.
I then check the pointer which is looking at array[0] to see if it is a valid character or punctuation. If pointer is valid then increment to next array index. The word counter is incremented when the first two tests fail. The function then will increment over any number of spaces until the next valid char is found.
The function ends when null '\0' or a new line '\n' character is found. Function will increment count one last time right before it exit to account for the word preceding null or newline. Function returns count to the calling function.
#include <ctype.h>
char wordCount(char array[]) {
char *pointer; //Declare pointer type char
pointer = &array[0]; //Pointer to array
int count; //Holder for word count
count = 0; //Initialize to 0.
long len; //Holder for length of passed sentence
len = strlen(array); //Set len to length of string
for (int i = 0; i < len; i++){
//Is char punctuation?
if (ispunct(*(pointer)) == 1) {
pointer += 1;
continue;
}
//Is the char a valid character?
if (isalpha(*(pointer)) == 1) {
pointer += 1;
continue;
}
//Not a valid char. Increment counter.
count++;
//Look out for those empty spaces. Don't count previous
//word until hitting the end of the spaces.
if (*(pointer) == ' ') {
do {
pointer += 1;
} while (*(pointer) == ' ');
}
//Important, check for end of the string
//or newline characters.
if (*pointer == '\0' || *pointer == '\n') {
count++;
return(count);
}
}
//Redundent return statement.
count++;
return(count);
}
I had this as an assignment...so i know this works.
The function gives you the number of words, average word length, number of lines and number of characters.
To count words, you have to use isspace() to check for whitespaces. if isspace is 0 you know you're not reading whitespace. wordCounter is a just a way to keep track of consecutive letters. Once you get to a whitespace, you reset that counter and increment wordCount. My code below:
Use isspace(c) to
#include <stdio.h>
#include <ctype.h>
int main() {
int lineCount = 0;
double wordCount = 0;
double avgWordLength = 0;
int numLines = 0;
int wordCounter = 0;
double nonSpaceChars = 0;
int numChars = 0;
printf("Please enter text. Use an empty line to stop.\n");
while (1) {
int ic = getchar();
if (ic < 0) //EOF encountered
break;
char c = (char) ic;
if (isspace(c) == 0 ){
wordCounter++;
nonSpaceChars++;
}
if (isspace(c) && wordCounter > 0){
wordCount++;
wordCounter =0;
}
if (c == '\n' && lineCount == 0) //Empty line
{
break;
}
numChars ++;
if (c == '\n') {
numLines ++;
lineCount = 0;
}
else{
lineCount ++;
}
}
avgWordLength = nonSpaceChars/wordCount;
printf("%f\n", nonSpaceChars);
printf("Your text has %d characters and %d lines.\nYour text has %f words, with an average length of %3.2f ", numChars, numLines, wordCount, avgWordLength);
}
Here is one solution. This one will count words correctly even if there are multiple spaces between words, no spaces around interpuncion symbols, etc. For example: I am,My mother is. Elephants ,fly away.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int countWords(char*);
int main() {
char string[1000];
int wordsNum;
printf("Unesi nisku: ");
gets(string); /*dont use this function lightly*/
wordsNum = countWords(string);
printf("Broj reci: %d\n", wordsNum);
return EXIT_SUCCESS;
}
int countWords(char string[]) {
int inWord = 0,
n,
i,
nOfWords = 0;
n = strlen(string);
for (i = 0; i <= n; i++) {
if (isalnum(string[i]))
inWord = 1;
else
if (inWord) {
inWord = 0;
nOfWords++;
}
}
return nOfWords;
}
this is a simpler function to calculate the number of words
int counter_words(char* a){`
// go through chars in a
// if ' ' new word
int words=1;
int i;
for(i=0;i<strlen(a);++i)
{
if(a[i]==' ' && a[i+1] !=0)
{
++words;
}
}
return words;}