I'm new to programming and I've decided to do some simple programming exercises.
The challenge is to remove all vowels from a user inputted string.
I've already wrote the code and I don't know why it isn't working.
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <ctype.h>
bool isVowel(char ch)
{
char charToBeTested = tolower(ch);
if(charToBeTested == 'a' || 'e' || 'i' || 'o' || 'u')
return true;
else
return false;
}
int main()
{
int i;
char formattedString[80];
printf("Enter a string: ");
scanf("%s", &formattedString);
for(i = 0; i < strlen(formattedString); i++)
{
if(isVowel(formattedString[i]) == true)
{
formattedString[i] = ' ';
}
}
printf("%s", formattedString);
return 0;
}
All it is supposed to do is check every character in the string and see if it's a vowel. If it's a vowel, replace the current character with a space. I will write the function to remove the spaces later.
All help is appreciated, sorry for being such a noob!
This code doesn't do what you think it does:
if (charToBeTested == 'a' || 'e' || 'i' || 'o' || 'u') {
...
}
C interprets this as
if ((charToBeTested == 'a') || 'e' || 'i' || 'o' || 'u') {
...
}
Here, the || operator is being applied directly to the character literals 'e', 'i', etc. Since C treats any nonzero value as "true," this statement always evaluates to true.
To fix this, try rewriting it like this:
if (charToBeTested == 'a' ||
charToBeTested == 'e' ||
charToBeTested == 'i' ||
charToBeTested == 'o' ||
charToBeTested == 'u') {
...
}
Alternatively, use a switch statement:
switch (charToBeTested) {
case 'a': case 'e': case 'i': case 'o': case 'u':
return true;
default:
return false;
}
Also, you might want to use tolower so that the testing is done case-insensitively.
Hope this helps!
This is incorrect:
if(charToBeTested == 'a' || 'e' || 'i' || 'o' || 'u')
correct is:
if(charToBeTested == 'a' || charToBeTested == 'e' || charToBeTested == 'i' || charToBeTested == 'o' || charToBeTested == 'u')
Or, you can create static table, like:
char vowels[0x100] = {
['a'] = 1,
['e'] = 1,
['i'] = 1,
['o'] = 1,
['u'] = 1,
};
And test by:
if(vowels[(unsigned char)charToBeTested])
You'll need to rewrite your isVowel function to something like:
bool isVowel(char ch)
{
char charToBeTested = tolower(ch);
if(charToBeTested == 'a') {
return true;
} else if(charToBeTested == 'e') {
return true;
} else if(charToBeTested == 'i') {
return true;
} else if(charToBeTested == 'o') {
return true;
} else if(charToBeTested == 'u') {
return true;
} else {
return false;
}
}
Alternatively, you can use a switch statement to do the same thing, like this:
bool isVowel(char ch)
{
char charToBeTested = tolower(ch);
switch(charToBeTested) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
return true;
default:
return false;
}
}
You need to test each alternative separately:
char c = tolower(ch);
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
Your original code is:
if (charToBeTested == 'a' || 'e' || 'i' || 'o' || 'u')
The compiler evaluates that as:
if ((charToBeTested == 'a') || true)
because 'e' is not zero and any expression which is not zero is true.
If it optimizes really thoroughly, can deduce that the whole expression will always be true, regardless of the value of charToBeTested, and hence it can reduce the entire function to return true (without ever needing to call tolower(). If it was a static function, it could even eliminate the function call altogether. Whether any compiler would actually be that aggressive is open to debate.
Just to add to everyones answer; as they say, you need to fix your testing criteria.
Also, don't forget to check for the Uppercase version too:
if (charToBeTested == 'a' ||
charToBeTested == 'e' ||
charToBeTested == 'i' ||
charToBeTested == 'o' ||
charToBeTested == 'u' ||
charToBeTested == 'A' ||
charToBeTested == 'E' ||
charToBeTested == 'I' ||
charToBeTested == 'O' ||
charToBeTested == 'U') {
...
}
Related
I'm trying to solve a problem with replacing letters with numbers. The user will enter a string, in case there are letters, I must substitute the corresponding number, and in case there are * # - symbols, I must simply remove them.
However, I am facing an issue. When the user types only a numeric string, the last character of this string is being removed, which cannot happen. This can only happen if there are letters or symbols in the string.
Source
#include <stdio.h>
#include <string.h>
void alterChars(char phrase[])
{
int i, dashes = 0;
for (i = 0; phrase[i] != '\0'; i++)
{
if (phrase[i] == 'A' || phrase[i] == 'B' || phrase[i] == 'C')
{
phrase[i] = '2';
}
if (phrase[i] == 'D' || phrase[i] == 'E' || phrase[i] == 'F')
{
phrase[i] = '3';
}
if (phrase[i] == 'G' || phrase[i] == 'H' || phrase[i] == 'I')
{
phrase[i] = '4';
}
if (phrase[i] == 'J' || phrase[i] == 'K' || phrase[i] == 'L')
{
phrase[i] = '5';
}
if (phrase[i] == 'M' || phrase[i] == 'N' || phrase[i] == 'O')
{
phrase[i] = '6';
}
if (phrase[i] == 'P' || phrase[i] == 'Q' || phrase[i] == 'R' || phrase[i] == 'S')
{
phrase[i] = '7';
}
if (phrase[i] == 'T' || phrase[i] == 'U' || phrase[i] == 'V')
{
phrase[i] = '8';
}
if (phrase[i] == 'W' || phrase[i] == 'X' || phrase[i] == 'Y' || phrase[i] == 'Z')
{
phrase[i] = '9';
}
if (phrase[i] == '*' || phrase[i] == '#' || phrase[i] == '-')
{
dashes++;
}
else if (dashes > 0)
{
phrase[i - dashes] = phrase[i];
}
}
phrase[strlen(phrase)-1] = '\0';
printf("%s\n", phrase);
}
int main()
{
char phrase[300];
while (!feof(stdin))
{
scanf(" %[^\n]s", phrase);
alterChars(phrase);
}
return 0;
}
Any tips will be valuable. You can access the problem to see where the error is occurring. Anyway, it's on the last entry, at number 190. It is being printed 19, but in fact it should be printed 190, because the removal of characters should only occur when there are letters, or symbols.
Examples
Input: 333-PORTO
Output: 33376786
The problem:
Input: 190
Output: 19
With your "generous" scanning, i.e. practically no expected syntax, you can simply loop while scanning is successful.
while (1==scanf(" %299[^\n]", phrase)) alterChars(phrase);
That fixes the problem with your while condition ( see Why is “while ( !feof (file) )” always wrong? ).
Then you want to read each line until either newline or terminator:
for (i = 0; phrase[i] != '\0' && phrase[i] != '\n'; i++)
And you want to force-terminate with respect to the dashes.
phrase[strlen(phrase)-dashes] = '\0';
and you get the desired output - and in only one line.... ;-)
The explanation is, if you always terminate as with 1 dash, then it works for 1 dash, fails by cutting too much for zero dashes and does other unwanted stuff for more than one dash, i.e. repeat the last few characters.
It is after all unrelated to "numeric only".
I have incorporated this good input by chux:
scanf(" %[^\n]s" is bad as it has not width limit and 2) the s is pointless.
Here is my attempt, after testing, it changes every lower letter in my string to upper and every upper letter to lower.
I think my fifth line of code somehow did not work, it changes every letter instead of just vowels. Please give me some advice on how to improve it?
(I'm forbidden to use string.h)
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX_STR_LEN 1024
void change_vowel(char somestr[MAX_STR_LEN])
{
for (int x = 0; somestr[x]!= '\0'; x+=1)
{
if ((somestr[x] == 'A' || somestr[x] == 'E' || somestr[x] == 'I' || somestr[x] == 'O' || somestr[x] == 'U'));
{
if (islower(somestr[x]))
{
somestr[x] = toupper(somestr[x]);
}
else
{
somestr[x] = tolower(somestr[x]);
}
}
}
}
Your code has two little mistakes, both in this line
if ((somestr[x] == 'A' || somestr[x] == 'E' || somestr[x] == 'I' || somestr[x] == 'O' || somestr[x] == 'U'));
The line ends with a semicolon ; which means, the code below will always get executed. To the compiler, this will (roughly, let's ignore the new block for now) look like that:
if ((somestr[x] == 'A' || somestr[x] == 'E' || somestr[x] == 'I' || somestr[x] == 'O' || somestr[x] == 'U'))
{
// Nothing here
}
if (islower(somestr[x]))
{
somestr[x] = toupper(somestr[x]);
}
else
{
somestr[x] = tolower(somestr[x]);
}
You wouldn't change lowercase vowels to uppercase, because you only check for uppercase vowels. I suggest adding a toupper() so it becomes toupper(somestr[x]) == 'A' or to have another if below which checks the lowercase vowels. The second approach would save the extra check if it is lower-/uppercase.
Here i get the answers for vowels but not for continue it says error for the continue and also for break.
#include < stdio.h >
main() {
char c, d;
printf("say your word to find the vowels\n");
scanf("%c", & c);
if (c == 'a' || c == 'A' || c == 'e' || c == 'E' || c == 'i' || c == 'I' || c == 'o' || c == 'O' || c == 'u' || c == 'U')
printf("you got a vowel\n");
else
printf("cool no vowel word\n");
printf("continue\n");
printf("(y/n)\n");
scanf("%c", & d);
if (d == 'y' || d == 'Y')
continue;
else
break;
return 0;
}
if (d == 'y' || d == 'Y')
continue; // where?
else
break; // what?
You have nothing to continue or break in your main function.
Both continue and break only make sense within a loop, so you should add a while(true) loop around the code in main() to repeat the whole thing until the user decides to quit.
Continue and break works in the loop block.. but here you have not added them in loop. Put the whole if block in the while(1) and it will work
#include <stdio.h>
int main()
{
char c;
int d;
while (1) {
printf("say your word to find the vowels\n");
scanf("%c", &c);
if (c == 'a' || c == 'A' || c == 'e' || c == 'E' || c == 'i' || c == 'I' || c == 'o' || c == 'O' || c == 'u' || c == 'U')
printf("you got a vowel\n");
else
printf("cool no vowel word\n");
printf("To continue enter 1\n");
scanf("%d", &d);
if (d == 1)
continue;
else
break;
}
return 0;
}
Check the continue and break statement syntax in the following link.
https://www.codingunit.com/c-tutorial-for-loop-while-loop-break-and-continue
I'm new to C, and I'm trying to improve a program's source code that I found in a book. I noticed that the source code contains a lot of "else if" conditions but has the same results, so I tried to compress them into a smaller code using || operator in the if function.
1st code:
#include <stdlib.h>
#include <stdio.h>
int main(){
char card_name[3];
puts("Enter the card_name: ");
scanf("%2s", card_name);
int val = 0;
if (card_name[0] == 'K'){
val = 10;
} else if (card_name[0] == 'Q'){
val = 10;
} else if (card_name[0] == 'J'){
val = 10;
} else if (card_name[0] == 'A'){
val = 11;
} else {
val = atoi(card_name);
}
printf("The card name value is %i\n", val);
return 0;
}
My improvement:
#include <stdlib.h>
#include <stdio.h>
int main(){
char card_name[3];
puts("Enter the card_name: ");
scanf("%2s", card_name);
int val = 0;
if (card_name[0] == 'K' || 'Q' || 'J' ){
val = 10;
} else if (card_name[0] == 'A'){
val = 11;
} else {
val = atoi(card_name);
}
printf("The card name value is %i\n", val);
return 0;
}
The problem with mine: When I write any another value it always prompt 10. What should I do ?
The issue is in C anything that is not 0 is a truthy value so in your code you have if (card_name[0] == 'K' || 'Q' || 'J'). This checks if card_name[0] == 'K' but this will always evaluate to true because you have || 'Q' and C treats 'Q' as truth. Here is the proper fix
#include <stdlib.h>
#include <stdio.h>
int main(){
char card_name[3];
puts("Enter the card_name: ");
scanf("%2s", card_name);
int val = 0;
if (card_name[0] == 'K' || card_name[0] == 'Q' || card_name[0] == 'J' ){
val = 10;
} else if (card_name[0] == 'A'){
val = 11;
} else {
val = atoi(card_name);
}
printf("The card name value is %i\n", val);
return 0;
}
This is not the correct expression:
(card_name[0] == 'K' || 'Q' || 'J' )
This will be always evaluate to true because 'Q' and 'J' are not 0.
You should write:
(card_name[0] == 'K') || (card_name == 'Q') || (card_name == 'J')
if (card_name[0] == 'K' || 'Q' || 'J' ){
val = 10;
}
'Q', etc is evaluated as a truth statement and since the value of the char is not 0 will always be true
should be
if (card_name[0] == 'K' || card_name[0] == 'Q' || card_name[0] == 'J' ){
val = 10;
}
if (card_name[0] == 'K' || 'Q' || 'J' )
should be
if (card_name[0] == 'K' || card_name[0] == 'Q' || card_name[0] == 'J' )
'Q' will always evaluate to true, you need the full comparison in each or.
Check the operator precedence in you if statement. If you look here http://en.cppreference.com/w/c/language/operator_precedence, you can see, that == has higher priority than ||.
The correct if statement should be like this:
if (card_name[0] == 'K' || card_name[0] == 'Q' || card_name[0] == 'J' ){
If you are not sure, what is the operator precedence, you can use brackets like this:
if ((card_name[0] == 'K') || (card_name[0] == 'Q') || (card_name[0] == 'J') ){
Note:
Your code is not correct, because if(card_name[0] == 'K' || 'Q' || 'J' ) is understood as if(card_name[0] == 'K' || true || true) which is always true
No, as many others have pointed out, using if (card_name[0] == 'K' || 'Q' || 'J' ) is wrong, and they have also described why and how to correct it. However, if you really just want a shorter and snappier way of writing the test, you could go for a switch-statement:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char card_name[3];
puts("Enter the card_name: ");
scanf("%2s", card_name);
int val = 0;
switch (card_name[0]) {
case 'K': /* fallthrough */
case 'Q': /* fallthrough */
case 'J': val = 10; break;
case 'A': val = 11; break;
default: val = atoi(card_name);
}
printf("The card name value is %i\n", val);
return 0;
}
Note that a switch statement is not a generic replacement for if-else if in C as each case needs to be constant integer expression (expressing it sloppily, a C book will tell you the restrictions correctly).
Always keep in mind ||means one of the condition must be true to proceed . if && is used , it checks all the condition and proceeds only if all the conditions satisfy. Pretty basic info for noobies...
for example when I type in a string "Hello", when I press 'a' it should print "There are 2 vowels." Instead, it says there are 0. I'm new to programming and this is the first language I am learning. Help?
/*
Student: Josiah Eleazar T. Regencia
Course: BSIT 1
Subject: SCS 101
Professor: Daniel B. Garcia
Problem definition:
Write a menu program that will count the vowels and consonants in the string
*/
#include <stdio.h> //printf and scanf functions
#include <string.h> //string functions
#include <stdlib.h>
#include <conio.h>
#define PROMPT "Type in a word, a phrase, or a sentence." //instucts the user
/*
Declaring the function for the user's menu
*/
void menu();
/*
Declaration of function needed to count the vowels in the string
*/
int vowel_count(char *stringInput); //declaring the function to count the vowels sounds
/*
Declaration of function needed to count the consonants in the stringn
*/
int consonant_count(char *stringInput); //declaring the functions to count the consonant sounds
/*
Declaring the function needed to convert the streeting to uppercase
*/
int uppercase(char *stringInput);
/*
Declaring the function needed to convert the streeting to uppercase
*/
int lowercase(char *stringInput);
int main () {
char userInput[100]; // the string the user inputs
char commandKey[1]; //this key is for the menu
char newInput[100]; //this is for the new input to user will put in
int stringLength; //to identify the length of the string
/*
Variables for counting the vowels and consonants
*/
int consonantCount;
printf("%s\n\n", PROMPT); //instucts the user
gets(userInput);
stringLength = strlen(userInput); //gets the length of the string
//fgets(userInput, 100, stdin);
/*if(stringLength > 0 && userInput[stringLength - 1] == '\n') {
userInput[stringLength - 1] ='\0';
}*/
menu(); //prints out the menu for the user to pick his options
/*
The loop will run what the user asks the program to run while at the same time also asking
what the programmer wants next
*/
while(*commandKey != 'X' || *commandKey != 'x') {
//int commandLength; //length of the command key
printf("Enter your menu selection: ");
gets(commandKey);
/*commandLength = strlen(commandKey);
fgets(commandKey, 100, stdin);
if(commandLength > 0 && commandKey[commandLength - 1] == '\n') {
commandKey[commandLength - 1] ='\0';
}*/
if(*commandKey == 'A' || *commandKey == 'a') {
int vowelCount;
vowelCount = vowel_count(userInput);
printf("There are %d vowels.\n\n", vowelCount);
}
if(*commandKey == 'B' || *commandKey == 'b') {
consonantCount = consonant_count(userInput);
printf("There are %d consonants.\n\n", consonantCount);
}
if(*commandKey == 'C' || *commandKey == 'c') {
/*
This condition simply converts the input string to all lowercase letters
*/
lowercase(userInput);
}
if(*commandKey == 'D' || *commandKey == 'd') {
/*
This condition simply converts the input string to all lowercase letters
*/
uppercase(userInput);
}
if(*commandKey == 'E' || *commandKey == 'e') {
/*
Prints the current string
if the string was converted in lowercase letters, the outcome would be all lowercase letters
if the string was converted in uppercase letters, the outcome would be all uppercase letters
*/
printf("%s\n\n", userInput);
}
if(*commandKey == 'F' || *commandKey == 'f') {
/*
When the user wants to test a new string, this is the condition for the user
to automatically ask of it
*/
printf("%s\n", PROMPT);
gets(newInput);
strcpy(userInput, newInput);
}
if(*commandKey == 'M' || *commandKey =='m') {
/*
In case the user forgets, this will serve as a reminder of the menu
*/
menu();
}
if(*commandKey == 'X' || *commandKey == 'x') {
printf("Goodbye!\n");
break;
}
}
}
//Function that displays the menu.
void menu() {
/*
These are the set of command keys given to the user
*/
printf("\n\n\n");
printf("PRESS:\n\n");
printf(" A - Count the number of vowels in the string.\n");
printf(" B - Count the number of consonants in the string.\n");
printf(" C - Convert the string to uppercase.\n");
printf(" D - Convert the string to lowecase.\n");
printf(" E - Display the current string.\n");
printf(" F - Enter another string.\n");
printf("\n");
printf(" M - Display this menu.\n");
printf(" X - Exit the program.\n");
printf("\n\n");
}
/*
Defining the function for the vowel counting
*/
int vowel_count(char *stringInput) {
if ( *stringInput == '\0')
return 0;
else
return vowel_count(stringInput + 1) + (*stringInput == 'a' || *stringInput == 'A')
+ (*stringInput == 'e' || *stringInput == 'E')
+ (*stringInput == 'i' || *stringInput == 'I')
+ (*stringInput == 'o' || *stringInput == 'O')
+ (*stringInput == 'u' || *stringInput == 'U');
}
/*
Defining the function for the vowel counting
*/
int consonant_count(char *stringInput) {
if (*stringInput == '\0')
return 0;
else
return consonant_count(stringInput + 1) + (*stringInput == 'b' || *stringInput == 'B')
+ (*stringInput == 'c' || *stringInput == 'C')
+ (*stringInput == 'd' || *stringInput == 'D')
+ (*stringInput == 'f' || *stringInput == 'F')
+ (*stringInput == 'g' || *stringInput == 'G')
+ (*stringInput == 'h' || *stringInput == 'H')
+ (*stringInput == 'j' || *stringInput == 'J')
+ (*stringInput == 'k' || *stringInput == 'K')
+ (*stringInput == 'l' || *stringInput == 'L')
+ (*stringInput == 'm' || *stringInput == 'M')
+ (*stringInput == 'n' || *stringInput == 'N')
+ (*stringInput == 'p' || *stringInput == 'P')
+ (*stringInput == 'q' || *stringInput == 'Q')
+ (*stringInput == 'r' || *stringInput == 'R')
+ (*stringInput == 's' || *stringInput == 'S')
+ (*stringInput == 't' || *stringInput == 'T')
+ (*stringInput == 'v' || *stringInput == 'V')
+ (*stringInput == 'w' || *stringInput == 'W')
+ (*stringInput == 'x' || *stringInput == 'X')
+ (*stringInput == 'y' || *stringInput == 'Y')
+ (*stringInput == 'z' || *stringInput == 'Z');
}
/*
Defining the function for the conversion of the string to all uppercase letters
*/
int uppercase(char *stringInput) {
while(*stringInput) {
*stringInput = toupper(*stringInput);
stringInput++;
}
}
/*
Defining the function for the conversion of the string to all uppercase letters
*/
int lowercase(char *stringInput) {
while(*stringInput) {
*stringInput = tolower(*stringInput);
stringInput++;
}
}
This loop will never stop:
while(*commandKey != 'X' || *commandKey != 'x')
A loop stops when its condition is false. For *commandKey != 'X' || *commandKey != 'x' to be false, it is logically equivalent for *commandKey == 'X' && *commandKey == 'x' to be true, which doesn't quite work. *commandKey can't be both 'X' and 'x'.
Instead, you want:
while(*commandKey != 'X' && *commandKey != 'x')
Which will stop when *commandKey is 'X' or 'x'.
Also, you never initialized commandKey, so you can't test it in the loop (using values of uninitialized variables is undefined behavior). And if you want to treat it as a string, you need to declare it such that it holds at least 2 characters, because the null character is needed:
char commandKey[2] = { 0 };
This will initialize commandKey to an empty string. Remember that gets() will null-terminate the string, so, even if your command is just one key, gets() will need at least 2 positions to fill - the character command and the null terminating byte. Alternatively, you can leave commandKey as is (provided that you initialize it), and use getchar() instead, which reads one single character.