As you might be able to tell im trying to introduce a counter for how many consonants there are in a certain string, but the output is always 50, unless spaces are involved.
int main(){
char input[50];
int total = 0;
cout << "Enter a string of no more than 50 characters\n";
cin.getline(input,50);
for(int n = 0; n<50;n++){
if(input[n]!='a',input[n]!='A',input[n]!='e',input[n]!='E',input[n]!='i',input[n]!='I',input[n]!='o',input[n]!='O',input[n]!='u',input[n]!='U',input[n]!=' ')
total++;}
cout << total << endl;}
According to wikipedia, comma operator is defined as follows
In the C and C++ programming languages, the comma operator
(represented by the token ,) is a binary operator that evaluates its
first operand and discards the result, and then evaluates the second
operand and returns this value (and type).
In your case, you should use logical AND (&&) instead of comma operation.
More efficiently, you may rewrite your code like this
char c = tolower(input[n]);
if (c >= 'a' && c <= 'z' && c != 'a' && c != 'e' && c != 'i' && c != 'o' && c !='u')
total++;
It will include all the cases.
As everyone has clearly explained, you need to use && operator to ensure all conditions are checked.
if(input[n]!='a' && input[n]!='A' && input[n]!='e' && input[n]!='E' && input[n]!='i' && input[n]!='I' && input[n]!='o' && input[n]!='O' && input[n]!='u' && input[n]!='U' && input[n]!=' '){
total++;
}
One recommendation to avoid multiple checks:
Extract the character to a variable converted to lower or upper case.
char c = input[n] | 32;
Regarding the ',' used; this program might provide more insight along with the WIKI shared :
void main(){
int a=-1;
if(++a,a, a++){ // Works like "||"
printf("Yes %d",a);
}else {
printf("NO %d", a);
}
}
Output: NO 1
Related
I am new for "C++" so I don't understand the following part of code.
The "data" is the String just like "Hello World" and seperature equals to this char "|". So what does it mean this line "data.charAt(i) == separator || i == maxIndex"
int maxIndex = data.length() - 1;
for (int i = 0; i <= maxIndex && found <= index; i++) {
if (data.charAt(i) == separator || i == maxIndex) {
found++;
strIndex[0] = strIndex[1] + 1;
strIndex[1] = (i == maxIndex) ? i+1 : i;
}
}
This:
data.charAt(i) == separator || i == maxIndex
is an expression that is contextually convertible to bool. That expression is part of the if statement condition. The || operator is a logical operator OR. Simply speaking you have:
if (A OR B)
Where A in your case is data.charAt(i) == separator and B is i == maxIndex. We can think of A and B as operands.
Due to operator precedence the compiler knows what A and B are and how to cut the entire expression into smaller expressions that make up operands. Both expressions have the equality operator == in them. So thinking about separator || i as being an expression is wrong.
The logical operator || groups left to right which means A gets evaluated first and B might not get evaluated if A is true.
Currently, I'm having some trouble implementing a parse integer program I've made. I get two yellow lines appearing under the function when it is called in the program
using namespace std;
char parseInt(char userInput[40], char& integers);
int main()
{
char userInput[40];
char integers[40];
cout << "After you enter string input, the program will parse all the integers "
<< "inside the string and display them. \n Enter a string: \n";
cin.ignore();
cin.getline(userInput, 40);
parseInt(userInput, integers); //Here lies the problem
cout << "The integers inside the string you entered were: \n" << integers;
return 0;
}
char parseInt(char userInput[40], char& integers)
{
int j = 0;
for(int i = 0; i<sizeof(userInput); i++)
{
if( userInput[i] == 1 || userInput[i] == 2 || userInput[i] == 3 ||
userInput[i] == 4 || userInput[i] == 5 || userInput[i] == 6 ||
userInput[i] == 7 || userInput[i] == 8 || userInput[i] == 9 ||
userInput[i] == 0 )
{
integers = userInput[i];
j++;
}
}
}
When the parse Int function is called, the two error messages I'm getting are :
-cannot bind rvalue (char) (char*) (&integers) to '(char&)'
-invalid conversion from 'char*' to char [-fpermissive]
I'm just having a hard time understanding exactly what the error codes are trying to say, I'm trying to understand them more.
Many bugs here.
sizeof(userInput) doesn't work like you expect (user4581301 mentioned this in a comment). userInput is a parameter, and due to parameter type adjustment.
The type of a function is determined using the following rules. The type of each parameter (including function parameter packs) is determined from its own decl-specifier-seq and declarator. After determining the type of each parameter, any parameter of type "array of T" or of function type T is adjusted to be "pointer to T". After producing the list of parameter types, any top-level cv-qualifiers modifying a parameter type are deleted when forming the function type.
As a result, your loop only goes up to sizeof (char*).
You are reading in a string but checking the numeric value of each character. Don't expect that '1' == 1, it's not true on any character encoding in common use. (EloyBG mentioned this one)
You declared integers as a reference to just one integer, but tried to pass a whole array. (Ilan mentioned this)
You're trying to stuff many values into a reference to just one integer. (EloyBG mentioned this too, but his fix is misleading for the same reason as #1)
Reaching the end of a non-void function is illegal, you have to return a value or leave abnormally (user4581301 mentioned this too)
The C way to fix it would be to pass the length of the array as a separate parameter. In C++, you can use a reference to array to either enforce a fixed length or even infer the actual length:
void parseInt(char (&userInput)[40], char (&integers)[40])
Parameter adjustment only changes arrays, not references to arrays, and therefore your sizeof attempt will again work.
In parseInt, integers is declared like single character but you are passing an array. Furthermore, you compare userInput as integer instead of as ASCII.
void parseInt(char userInput[40], char integers[40])
{
int j = 0;
for(int i = 0; i<sizeof(userInput); i++)
{
if( userInput[i] == '1' || userInput[i] == '2' || userInput[i] == '3' ||
userInput[i] == '4' || userInput[i] == '5' || userInput[i] == '6' ||
userInput[i] == '7' || userInput[i] == '8' || userInput[i] == '9' ||
userInput[i] == '0' )
{
integers[j] = userInput[i];
j++;
}
}
}
If you use your code,
It return a single character by reference, but not return a chain of characters.
char parseInt(char userInput[40], char& integers)
{
int j = 0;
for(int i = 0; i<sizeof(userInput); i++)
{
Here, you are comparing the userInput with the first elements of the ASCII table.
if( userInput[i] == 1 || userInput[i] == 2 || userInput[i] == 3 ||
userInput[i] == 4 || userInput[i] == 5 || userInput[i] == 6 ||
userInput[i] == 7 || userInput[i] == 8 || userInput[i] == 9 ||
userInput[i] == 0 )
{
In the next line, you change the value of the single character but you do not adding a new character, because it is not a array (I supuse you got the idea because you declare j)
integers = userInput[i];
j++;
}
}
}
In the main,
cin.ignore()
is unnecesary,it makes that you lose the first character of the chain.
Declare integers like an array of characters
Compare userInput as ASCII not as integer (you can compare it as integer but you have to use the integer that corresponds with the character on the ASCII table)
Delete the cin.ignore() line
You are passing in char integers[40] into a function that it's second parameter requires a char to be passed by reference.
change char& to char[40]
char parseInt(char userInput[40], char integers[40])
My target is to validate c++ input that it will hold only small and capital letters and empty space. Can I do that without for loop? My current code is:
bool validateInput()
char c;
string result;
cin >> result;
for (int i = 0; i < result.length(); i++) {
c = result.at(i);
if ( !( ( c >= 'a' && c <= 'z' ) || ( c >= 'A' && c <= 'Z' ) || c == ' ' ) )
{
return false;
}
}
}
You can do it without a for loop, although you'll obviously still need to use a loop, I guess the modern C++ way would be to use std::find_if , ( you can also use std::none_of as pointed out by #NathanOliver which wraps std::find_if and returns a boolean instead of an iterator ). It's also probably a good idea to use std::isalpha, partly because a character set might not have alphabetical characters mapped to decimal values in order, and partly because it is easier to write :-)
bool validateInput()
{
std::string result;
std::cin >> result;
return std::none_of(result.begin(), result.end(), [](const char& c)
{
return !(std::isalpha(c) || c == ' ');
});
}
I'm trying to create a program that removes vowels from a string, add them into a vector and then give the user the possibility of having the original code again.
In my code i have this:
char s[20];
And soon after i have this comparison:
for(j=0;j<tam;j++)
{
if(strcmpi(s[j],"a")==1 ||
(strcmpi(s[j],"e")==1 ||
(strcmpi(s[j],"i") ==1||
(strcmpi(s[j],"o") ==1||
(strcmpi(s[j],"u")==1))
{
So if the array is char and the vowels are char(""), why the compiler give me this error?:
[Warning] passing arg 1 of `strcmpi' makes pointer from integer without a cast
EDIT
As someone said the correct is s[j] == 'a', but that result in wrong way. If a put car the result is still car. Don't know why.
if(s[j] == 'a' ||
s[j] == 'A' ||
s[j] == 'e' ||
s[j] == 'E' ||
s[j] == 'i' ||
s[j] == 'I' ||
s[j] == 'o' ||
s[j] == 'O' ||
s[j] == 'u' ||
s[j] == 'U')
{
s[j] = s[j++]; }
Strcmpi is for comparing strings. The first argument to strcmpi is of type char, when it expects a char*.
In order to compare single chars, s[j]=='e' is enough, or tolower(s[j])=='e' if you need it to be case insensitive. You'll need to include ctype.h. for tolower.
The arguments to strcmpi must be strings, but s[j] is just a single character, not a string. You can use == to compare characters directly. To get case-insensitive comparisons, get the lowercase version of the character first and compare it.
for (j = 0; j < tam; j++) {
char lower = tolower(s[j]);
if (lower == 'a' || lower == 'e' || lower == 'i' || lower == 'o' || lower == 'u') {
...
}
}
You don't want to use strcmp or any of its variants.
Because you want to know whether the string contains vowels or not, you may want to use a substring search using strstr.
You use function strcmpi incorrectly. It first parameter has type const char * while you pass an argument of type char. That is the function expects a string while you pass only one character.
Moreover this function is not a standard C/C++ function. So it should not be used.
You could achieve the same result using the following approach
char vowels[] = "aeiou";
//...
if ( strchr( vowels, tolower( s[j] ) )
{
std::cout << s[j] << " is a vowel" << std::endl;
}
You have already been told that strcmpi is not the right way to check single characters. This is an answer to the edit to your question, where you ask about actually stripping the vowels.
If you want to retain the original string, you need extra memory for the string without consonants. You also need two indices, because once you have skipped a vowel in the original string, the indices are out of sync. Here's an example implementation:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main()
{
char orig[] = "Jackdaws love my big sphinx of quartz.";
char cons[sizeof(orig)]; // Make new char buffer as big
// as the original
int i, j;
j = 0;
for (i = 0; orig[i]; i++) {
if (strchr("AEIOUaeiou", orig[i]) == NULL) {
cons[j++] = orig[i];
}
}
cons[j] = '\0'; // Terminate consonant string
printf("was: '%s'\n", orig);
printf("is: '%s'\n", cons);
return 0;
}
The expression strchr checks whether a character is in a string. You can use it as a shortcut to spelling out all vowels in explicit comparisons.
I'm sure this has been asked a few times but the other questions I looked at didn't really help me much. Alright so here goes: I've got three functions one that converts an infix expression to a postfix, one that's a preprocessor and one that evaluates the postfix expression. What I'm having trouble with is evaluating a unary negative expression. If I put in my entire code it'll be super long so I'm only going to post up the parts that deal with the negative/minus case:
here's my output:
input: -3
after preprocess: 3
postfix = -3
then a segmentation fault when it should output " total = -3 "
#include "postfix.h"
#include "stack.h"
#include <cstdlib>
#include <cmath>
#include <cstdio>
void eval_postfix(char* postfix){
Stack<double> stack;
char fchar[100];
int j=0;
double a, b, convert, total = 0.0;
for(int i=0; postfix[i] != '\0'; i++){
switch(postfix[i]){
case '-':
a = stack.top();
stack.pop();
b = stack.top();
stack.pop();
total = b-a;
stack.push(total);
break;
I'm pretty sure the error is in that part of the function, I've been trying different things but nothing has been working, more times than not I get a segmentation fault or a zero. I originally tried to apply what I did in the infix2postfix expression (which obviously didn't work) But here's the rest of my code for the negative/minus case...
void infix2postfix(char* infix, char* postfix){
Stack<char> stack;
stack.push('\0');
int pc = 0;
bool c;
for(unsigned int i = 0; infix[i] != '\0'; i++){
//use the switch method to define what to do for each of the operators
switch(infix[i]){
case '-':
c = 0;
//unary negative
if(i==0){
postfix[pc++] = infix[i];
c = 1;
}
else if((infix[i-1] == '*' ||
infix[i-1] == '^' ||
infix[i-1] == '*' ||
infix[i-1] == '/' ||
infix[i-1] == '+' ||
infix[i-1] == '-')&&
i>0){
postfix[pc++]= infix[i];
c=1;
}
else{
if(stack.top() == '*' || stack.top() == '/' || stack.top() == '^'){
while(stack.top() != '\0' && stack.top() != '('){
postfix[pc++] = stack.top();
postfix[pc++] = ' ';
stack.pop();
}
}
}
if (c==0)
stack.push('-');
break;
void preprocessor(char* input){
char output[100];
int oc = 0;
for(unsigned int i=0; input[i] != '\0'; i++){
if((input[i] == '-' && (input[i-1] == '*' || input[i-1] == '^' || input[i-1] == '*'
|| input[i-1] == '/' || input[i-1] == '+' || input[i-1] == '-')
&& i>0)){
//output[oc++] = '0';
output[oc++] = input[i];
}
I'm almost certain that whatever error it is I made (or whatever edit I need to do) is probably something really simple that I just can't see (cause that's usually the case with me) but any nudge in the right direction would be highly appreciated!
**Note: the formatting of my code may not be accurate cause I only copied and pasted the parts I felt were relevant.
It seems to me like what is happening is that your code that evaluates the postfix expression, when it sees a minus sign, treats it as a subtraction. In particular, probably you push 3 onto the stack, and then encounter a minus sign: this triggers the code in the first block you posted, which tries to pop two elements off of the stack and subtract them. However there is only one element on the stack, namely the 3.