Comparing only the first elements of two differing arrays - c++

When I run this, the if statement is supposed to compare only the first element of both arrays. It works fine as long as array "ans" only contains y or Y, but if I enter a "yes", etc, it comes back false and shoots down to else.
char y[2]= "y";
char n[2] = "n";
char ans[5];
printf("Answer yes of no. (y/n) ");
scanf(" %s", ans);
if (strcasecmp(&ans[0], &y[0]) == 0)
{
printf("You said yes.\n");
printf("%c, %s\n", y[0], ans);
}
else if (strcasecmp(&ans[0], &n[0]) == 0)
{
printf("You said no.\n");
}
else
{
printf("hmm?\n");
}

Not really, strcasecmp() compares two strings, not two characters, even if you pass it the pointer to their first characters, it still compare two strings that start from this character until a terminating '\0'.
You can compare their first characters ignoring case like this:
if (toupper(ans[0]) == toupper(y[0])))

Use strncasecmp instead of strcasecmp, so that you can compare just the first character rather than the entire string. Change:
if (strcasecmp(&ans[0], &y[0]) == 0)
to:
if (strncasecmp(ans, y, 1) == 0)
and similarly for the rest.

Related

Why does typing three non-integers cause this function to recurse infinitely?

I've set up a script that asks the user to input a number that's two digits long at most.
But if the user types three non-integers in, like 'fff', the recursive function promptGetAge() fires infinitely.
Why?
int promptGetAge(){
char myString[3];
cout<<"How old is your dog? ";
cin.getline(myString,3,'\n');
int userStringToInt = atoi(myString);
if(userStringToInt==0 && !(myString=="0\0")){
promptGetAge();
} else {
return userStringToInt;
}
}
int main(){
cout<<"Your dog is "<<promptGetAge()<<" years old!"<<endl;
return 0;
}
Use the strcmp() function in <cstring> to compare content of strings, not == (which compares only the address of the first character). i.e. instead of myString == "0\0" use strcmp(myString, "0") == 0.
Or, better yet, use the string type in <string>. Then you can use == for comparison.
Note that string literals have a '\0' character appended anyway, and strcmp() searches for the first one it finds. So there is no functional difference between strcmp(myString, "0") and strcmp(myString, "0\0")
And don't use recursion to go back and repeat an action. Use a loop.

C++ matching a specific string

I have a function here that checks a text file for the existence of a string. The problem I have right now is that it's checking for substrings, so if the file has the word "IronMan" and any part of that string will pass the check.
Here's my code for the function:
void UIFunctions::checkIfExists()
{
while (!fin.eof())
{
getline(fin, line);
if (line.compare(getFriendName()) == string::npos)
{
setExists(false);
cout << getExistsErrorPrompt() << endl << endl;
if (listAfterCheck == 1)
{
listUsers();
}
cout << endl;
cout << endl;
cout << getErrorPrompt();
}
}
}
I searched for solutions and read that line.compare (changed from line.find) is what I need to match entire strings but instead of accepting substrings (like line.find did) now it doesn't accept anything at all to pass the check.
Edit: Also the file that this function uses would look something like this:
Ironman Captain Thor
The problem is that you are assuming that compare returns the same value as find would. The compare function returns an integer with value:
0 if the strings are equal
>0 if the compared string (in your case line) is lexicographically first
<0 if the comparing string (in your case getFriendName()) is lexicographically first
Therefore to check for an exact match, you would want:
if(line.compare(getFriendName()) == 0) {
setExists(false);
// ...
}
Comparing the result of compare with string::npos will never trigger since the magnitude of compare is the first differing character between your two strings.
std::basic_string::compare returns a value less than 0, 0 or more than 0. Since
if (line.compare(getFriendName()) == string::npos)
Is seeing if the return is the maximum value of the type of string::npos you more than likely will never trigger the if statement. If you only want to match a string exactly then you can use
if (line == getFriendName())
If instead you want to find any line that starts with getFriendName() then you want
if (line.find(getFriendName()) == 0)
In the above find will only return 0 if the string starts with what you want.

if,else how to write a math quit

i want to write a math test
EX:i input a right number,then i can get point.
finally,i can get the total score.
there is my attempt.
but,when i input a wrong number,i always get point.
what should i do?
char a;
int b;
char d;
b=0;
printf("1+1=\n");
a=getchar();
if(a=2){
printf("you got%d \n",b=b+10);
}else{
printf("you got%d \n",b);
}
printf("1+2=\n");
d=getchar();
if(d=3){
printf("you got%d \n",b=b+10);
}else{
printf("you got%d \n",b);
}
return 0;
You need to use if (a == '2') rather than if (a=2).
The former:
tests the value of a, unlike the latter which assigns a
compares a with the character '2', rather than the number 2.
If you are trying to compare in the If statement, then you should use comparison operator == and not assignment operator =.
Also if you're comparing characters , you need to use character quotes ''
Eg.
if(a=='2')
{
printf("you got%d \n",b=b+10);
}

recursive function has out_of_range exception

Given a global vector list of ASCII codes and corresponding number values and a string, like 000.00-000.0.0.0, this function takes an input token strings 2-char or 3-char long and replaces it with a single ASCII symbol that represents the number value between 0 and 184, then returns the shortened string without deliminator as out. Also, in reverse (direction 1) given the ASCII symbol it converts back to the number string and returns.
//looks for input string in vector and returns output, 'c' is check row, 'r' is return row
string vectorSearch(string &check, int n, int c, int r)
{
if (check.length() <= 1)
return check;
if (list[n][c] == check || list[n][c] == ('0'+check)) //adds leading zero if 2char long
return list[n][r];
else
return vectorSearch (check, ++n, c, r);
}
//this function takes an ontology and either changes from single char
//to string or takes strings and converts to char representation
string Lexicon::convertOntology(string input, int direction, string out, string temp)
{
if (input == "" && temp == "")
return out; //check for completed conversion
else {
if (input[0] == '.' || input[0] == '-' || input == "") { //found deliniator or endk
if (input != "") return convertOntology(input.substr(1),direction,
out+=vectorSearch(temp, 0, direction, 1-direction), "");
else return convertOntology("", direction,
out+=vectorSearch(temp, 0, direction, 1-direction), "");
} else
return convertOntology(input.substr(1), direction, out, temp+=input[0]); //increment and check
}
}
These functions work fine except for on output after the last char is parsed. With a break on the line return convertOntology(input.substr(1), direction, out+=add, temp); there is an error when input == "" and temp == "0" - the last pass through vectorSearch() should clear the temp and add the temp char to the out string, since the temp is == 1char then it should be returned from vectorSearch() as it is. Then clear the convertOntology() return check of input and temp == "". But, it never reaches a break on the first line of vectorSearch() and there is an
Unhandled exception at 0x77bc15de exception: std::out_of_range at memory location 0x0035cf1c
What is going on? Is this an issue with recursion backtracking through returns and I am missing a return somewhere to break the recursion loop?
for the case where temp == "" and input != "" you call input.substr(1) which is, well, out of range.
Even if you don't get to the else part,
input.substr(1)
will throw an exception when the input string is exactly one character long.
Seems it doesn't - input.substr(input.size()) is allowed, and returns an empty string.
You will later likely have a similar problem in VectorSearch. If there is no match, you will increment n until it gets out of range.

How to figure out if the first index in an array is a negative sign

I am trying to write a bool function that looks at the first index in an array which contains a positive or negative number and classifies if it is a negative sign (i.e. -). If it is a negative Sign it returns false everything else returns true. I am trying to figure out how to compare the negative sign. The following code give an error because of the '-'
bool BigNum::get_positive() const
{
char '-';
if(digits[0] == '-')
{
return false;
}
else
{
return true;
}
}
char '-';
The compiler thinks you're trying to declare a char, but that's not a valid declaration.
Your entire function could be replaced with:
return (digits[0] != '-');
Of course, this is assuming that [0] is a valid index of digits. If not, bad things will happen. If you know the length of the array, you can do a check like this:
if( digits_length < 1 )
return false;
return (digits[0] != '-');
you must delete or comment "char '-';"
Mistake lies in line char '-'.
'-' is supposed to be stored in some variable which later could be used in if clause to compare. This is a syntactical error because you havn't defined a storage for '-'.
Otherwise as pointed above just delete this line and get away with using '-' in if (as you have already done it)