Implicit conversion from char* to bool - c++

I managed to solve my problem, it working properly and giving the correct results. The problem now is that I have this warning: Implicit conversion from char* to bool[readability-implicit-bool-conversion].
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
bool is_letter(const char s) {
return ('a' <= s && s <= 'z') || ('A' <= s && s <= 'Z');
}
int main() {
const int MAX_LENGTH = 260;
const int VOWELS = 11;
char is_vowel[VOWELS] = "aeiouAEIOU", s[MAX_LENGTH];
ifstream fin("date.in");
int k;
cin >> k;
int start = -1,nrVowels = 0, finish = 0, counter = 0;
while (!fin.eof()) {
fin.getline(s, MAX_LENGTH);
int n = strlen(s);
int have_word = 0;
for (int i = 0; i < n; ++i) {
if (is_letter(s[i])) {
have_word = 1;
if (strchr(is_vowel, s[i])) {
++nrVowels;
}
if (counter == 0) {
start = i;
finish = i;
++counter;
} else {
finish = i;
}
} else if (have_word == 1) {
if (nrVowels >= k) {
for (int i = start; i <= finish; ++i) {
cout << s[i];
}
cout << "\n";
}
counter = 0;
have_word = 0;
nrVowels = 0;
}
}
if (have_word == 1) {
if (nrVowels >= k) {
for (int i = start; i <= finish; ++i) {
cout << s[i];
}
cout << "\n";
}
counter = 0;
nrVowels = 0;
finish = 0;
}
}
return 0;
}
The error appears on the line where I am searching for the vowels
"
if (strchr(is_vowel, s[i]))
"

strchr() returns a char *. You're then using it in a boolean operation. While it works, the compiler is suggesting you change the code to:
if (strchr(...) != nullptr)
Then there is no implicit conversion.
Note that there are people who think C++ implicit conversion should be removed. Jason Turner has a talk on this on YouTube. I have no idea how many bugs I've had over the years due to implicit conversion, which is why your compiler warns you about it.

Related

isPalindrome homework exercise

Write a program that uses the function isPalindrome given in Example 6-6 (Palindrome). Test your program on the following strings:
madam, abba, 22, 67876, 444244, trymeuemyrt
Modify the function isPalindrome of Example 6-6 so that when determining whether a string is a palindrome, cases are ignored, that is, uppercase and lowercase letters are considered the same.
The isPalindrome function from Example 6-6 has been included below for your convenience.
bool isPalindrome(string str)
{
int length = str.length();
for (int i = 0; i < length / 2; i++) {
if (str[i] != str[length – 1 – i]) {
return false;
} // if
} // for loop
return true;
}// isPalindrome
Your program should print a message indicating if a string is a palindrome:
madam is a palindrome
My program so far is this
#include <iostream>
#include <string.h>
using namespace std;
int main () {
bool isPalindrome (string str);
string str;
int length = str.length();
cout << "Enter a string: ";
getline (cin,str);
for (int i = 0; i < length / 2; i++) {
if (str[i] != str[length -1 -i]) {
cout << str << "Is not a Palindrome";
return false;
} else if (str[i] == str[length -1 -i] && toupper(str[i]) != islower(str[i])) {
cout << str << "Is a Palindrome";
} // for loop
return true;
}
}
I do not know what im doing wrong I sent everything to make sure it matches the word backwards and then when it is true it will return true. I am very to new to programming and I am sorry if my code is a little sloppy.
This is a modification of your code. It wasn't too logical that you were declaring the function inside so i just put it outside.
#include <iostream>
#include <string.h>
using namespace std;
bool isPalindrome(string str) {
int length = str.length();
for (int i = 0; i < length / 2; i++) {
if (str[i] != str[length -1 -i]) {
cout << str << "Is not a Palindrome";
return false;
} else if (str[i] == str[length -1 -i] && toupper(str[i]) != islower(str[i])) {
cout << str << "Is a Palindrome";
} // for loop
return true;
}
return false;
}
int main () {
string str;
cout << "Enter a string: ";
getline (cin,str);
isPalindrome(str);
}
public static bool IsPalindrome(string value)
{
int i = 0;
int j = value.Length - 1;
while (true)
{
if (i > j)
{
return true;
}
char a = value[i];
char b = value[j];
if (char.ToLower(a) != char.ToLower(b))
{
return false;
}
i++;
j--;
}
}
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX 1000
bool isPalindrome(int x){
int c[MAX];
int i = 0;
int j;
int k = 0;
bool z;
if(x < 0){
return false;
}
while (x != 0){
int r = x % 10;
c[i] = r;
i++;
x = x / 10;
}
for (j = i - 1; j > -1; j--) {
printf("%d ", c[j]);
}
for(k = 0; k <= (i / 2); k++){
if(c[k] == c[i - k - 1]){
z = true;
}
else
{
z = false;
}
}
return z;
}

How can I compare the elements in a vector?

I took a look online and none of the answers solves the problem I have comparing the elements from a vector.
I tried implementing a bool function but the problem is the same.
I am pretty new in c++ so please be patient!
PART2: First of all thank you.
So I changed my programm and created a bool function, the problem is now that it doesn get recognised before 5-6 tries.
#include <iostream>
#include <vector>
#include <time.h>
#include <stdlib.h>
#include <string>
using namespace std;
vector<int> input, compareMe, randomNumbers;
const unsigned int MAX_VEKTORSTELLEN = 5;
const unsigned int UPPER_GRENZE = 49;
const unsigned int LOWER_GRENZE = 1;
unsigned int i, j;
string output;
int random, anzahlRichtige, eingabe;
bool isEqual = false;
string lotto(vector<int>)
{
if (input[i] < LOWER_GRENZE || input[i] > UPPER_GRENZE)
{
output = "Die Zahlen muessen zwischen 1 und 49 liegen! \n";
input.pop_back();
}
else if (input.size() != MAX_VEKTORSTELLEN)
output = "Es muessen 6 Zahlen uebergeben werde! \n";
else if (isEqual == true)
output = "Es duerfen keine doppelten Zahlen vorkommen! \n";
else
for (i = 0; i <= MAX_VEKTORSTELLEN; i++)
srand((unsigned)time(NULL) <= UPPER_GRENZE && (unsigned)time(NULL) > 0);
random = rand();
randomNumbers.push_back(random);
return output;
}
bool compare()
{
compareMe = input;
for (i = 0; i < input.size(); i++)
for (j = 0; j < compareMe.size(); j++)
if (compareMe[j] == input[i])
isEqual = true;
return isEqual;
}
int main()
{
cout << "insert 6 numbers: ";
while (cin >> eingabe)
{
input.push_back(eingabe);
lotto(input);
compare();
cout << output;
for (i = 0; i < input.size(); i++) //Debug
cout << input[i] << ", ";
continue;
}
for (i = 0; i < input.size(); i++)
cout << input[i];
system("pause");
return 0;
}
From line 34 to line I didn´t finish to code but doesn´t really matter because I got stuck before.
All your loops in lotto are wrong. You go one past the end of your containers.
for (i = 0; i <= input.size(); i++)
// ^ !!!
It should be <.
You got this right in main.

Passing an array from

Hi I am attempting to create a chess board to reintroduce myself to c++. I am having trouble with adding a member function to my array that the chess board is located in.
I believe I am structuring the problem incorrectly.
.cpp file:
#include "spaces.h"
#include <iostream>
char board::spaceLetter() {
return letter;
}
char board::spaceNumber() {
return number;
}
string board::getColor(board a) {
if (a.color() == true) //Also an error but not a big deal
return "black";
else
return "white";
}
void board::printBoard(board a[][8]) {
for (int i = 1; i <= 8; i++) {
for (int j = 1; j <= 8; j++) {
if (a[i][j].color() == true) { //This is where my problem is
cout << "w";
}
else
cout << "b";
}
cout << endl;
}
}
Header .h
#pragma once
#include <iostream>
using namespace std;
class board {
private:
int boardSpace[8][8];
bool color;
char number;
char letter;
public:
board(){
for (int i = 1; i <= 8; i++) {
for (int j = 1; j <= 8; j++) {
if (((i + j) % 2) == 0)
color = true; //black space
else
color = false;
}
}
}
char spaceLetter();
char spaceNumber();
string getColor(board);
void printBoard(board a[][8]);
};
Thank you!
Welcome to SO.
if (a.color() == true) //Also an error but not a big deal
color is not a function. It is a member variable. Remove the () from color().
Same mistake here:
if (a[i][j].color() == true)
Try running the code here and see if it works for you: https://rextester.com/GRG48268

LRU c++ program

I've been working on a program in one of my college classes. I have been having trouble with the implementation of my LRU code as it is not displaying any errors or anything, but compiles. There are two parts. The main that we input the values into, which we then specify which algorithm we want to use to find page faults. I know the main works, along with the FIFO algorithm, but I'm not getting anything with my LRU code (It compiles and "runs" but displays nothing as if I did not click to use the algorithm). Can anyone help me figure out what is wrong?
main.cpp
#include <iostream>
#include <string>
//#include "fifo.cpp"
#include "lru.cpp"
//#include "optimal.cpp"
using namespace std;
int main() {
// List of different variables
string pagestring;
int fs,pn[50], n;
// Prompt for page references
cout<<"Virtual Memory Simulation\nBy blah\n----------\nEnter the number of pages : " << endl;
cin >> n;
cout<<"\n-------------\nPlease enter a list of page numbers separated by commas.\n"<< endl;
cin>>pagestring;
// algorithm to use
char algo;
while (true) {
// Prompt algorithm to use
cout<<"----------\nPlease select an algorithm to use.\n\n1: First-In-First-Out (FIFO)\n2: Least-Recently-Used (LRU)\n3: Optimal\n0: Quit\n"<<endl;
cin>>algo;
if (algo == '1') {
//fifo(pagestring);
}
else if (algo == '2'){
LRU_Execute(pagestring, n);
}
else if (algo == '3'){
cout<<"Optimal Not yet coded"<<endl;
}
else if (algo == '0'){
break;
}
else {
cout<<"Invalid choice. Please try again."<<endl;
}
}
cout<<"Goodbye!!"<<endl;
};
LRU.cpp
#include <iostream>
#include <string>
using namespace std;
class pra
{
int fs,z;
int frame[50], frame1[50][2], pn[50], n, cnt, p, x;
public:
pra();
void init(string pagestring);
void getdata(string pagestring, int n);
void lru(int* pn, int n, string pagestring);
};
pra::pra()
{
int i;
for (i = 0; i < fs; i++)
{
frame[i] = -1;
}
for (i = 0; i < fs; i++)
{
frame1[i][0] = -1;
frame1[i][1] = 0;
}
p = 0;
cnt = 0;
}
void pra::init(string pagestring)
{
int i;
for (i = 0; i < fs; i++)
{
frame[i] = -1;
}
for (i = 0; i < fs; i++)
{
frame1[i][0] = -1;
frame1[i][1] = 0;
}
p = 0;
cnt = 0;
}
void pra::getdata(string pagestring, int n)
{
fs=3;
// index to loop through input string
int i = 0;
// current input string character
char z = pagestring[i];
int x = 0;
//cout << "\nEnter the page numbers : ";
while (z != '\0'){
// skip over commas and spaces
if (!(z == ',')) {
pn[x] = z;
x++;
// cout<<pn[x]<<"-This is pn[x]\n";
}
z = pagestring[++i];
}
//cout<<pn[x]<<"-This is pn[x] AGAIN\n";
this->lru(pn, n, pagestring);
}
void pra::lru(int* pn, int n, string pagestring)
{
init(pagestring);
int ind = 0, fault = 0, pi = 0, j, fn;
char i, z;
p = 0;
cnt = 0;
int min;
cout<<n<<"---"<<i<<" - "<<j<<" - "<<" - "<<fn<<" - "<<z;
for (i = 0; i < fs; i++)
{
frame1[i][0] = -1;
frame1[i][1] = 0;
}
pi = 0;
for (i = 0; i < n; i++)
{
j = 0;
if (ind > fs - 1)
ind = 0;
fault = 1;
min = 999;
while (j < fs)
{
if (frame1[j][0] = pn[pi])
{
fault = 0;
p++;
frame1[j][1] = p;
goto l2;
}
if (frame1[j][1] < min)
{
min = frame1[j][1];
fn = j;
}
j++;
}
j = 0;
while (j < fs)
{
if (frame1[j][0] = -1)
{
fault = 1;
fn = j;
goto l2;
}
j++;
}
ind++;
l2:
if (fault == 1)
{
p++;
frame1[fn][0] = pn[pi];
frame1[fn][1] = p;
cnt++;
}
cout << "\nElement: " << pn[pi];
pi++;
for (z = 0; z < fs; z++)
{
cout << "\t" << frame1[z][0];
}
if (fault == 1)
cout << "\t**Page Fault**";
else
cout << "\t--No Page Fault--";
}
cout << "\nTotal number of page faults: " << cnt;
cout << "\n";
}
void LRU_Execute(string pagestring, int n)
{
pra p;
int j, fault = 0, i, pi, z, fn, ind = 0, ans, ch;
p.getdata(pagestring, n);
//p.lru();
while (ans == 1);
//return 1;
}

C++: Change of base function (i.e. hex to octal, decimal, etc.) - Output slightly off for hex values

I need to create a generic function that changes from any starting base, to any final base. I have everything down, except my original function took (and takes) an int value for the number that it converts to another base. I decided to just overload the function. I am Ok with changing between every base, but am slightly off when using my new function to take in a string hex value.
The code below should output 1235 for both functions. It does for the first one, but for the second, I am currently getting 1347. Decimal to Hex works fine - It's just the overloaded function (Hex to anything else) that is slightly off.
Thanks.
#include <iostream>
#include <stack>
#include <string>
#include <cmath>
using namespace std;
void switchBasesFunction(stack<int> & myStack, int startBase, int finalBase, int num);
void switchBasesFunction(stack<int> & myStack, int startBase, int finalBase, string s);
int main()
{
stack<int> myStack;
string hexNum = "4D3";
switchBasesFunction(myStack, 8, 10, 2323);
cout << endl << endl;
switchBasesFunction(myStack, 16, 10, hexNum);
return 0;
}
void switchBasesFunction(stack<int> & myStack, int startBase, int finalBase, int num)
{
int totalVal = 0;
string s = to_string(num);
for (int i = 0; i < s.length(); i++)
{
myStack.push(s.at(i) - '0');
}
int k = 0;
while (myStack.size() > 0)
{
totalVal += (myStack.top() * pow(startBase, k++));
myStack.pop();
}
string s1;
while (totalVal > 0)
{
int temp = totalVal % finalBase;
totalVal = totalVal / finalBase;
char c;
if (temp < 10)
{
c = temp + '0';
s1 += c;
}
else
{
c = temp - 10 + 'A';
s1 += c;
}
}
for (int i = s1.length() - 1; i >= 0; i--)
{
cout << s1[i];
}
cout << endl << endl;
}
void switchBasesFunction(stack<int> & myStack, int startBase, int finalBase, string s)
{
int totalVal = 0;
for (int i = 0; i < s.length(); i++)
{
myStack.push(s.at(i) - '0');
}
int k = 0;
while (myStack.size() > 0)
{
totalVal += (myStack.top() * pow(startBase, k++));
myStack.pop();
}
string s1;
while (totalVal > 0)
{
int temp = totalVal % finalBase;
totalVal = totalVal / finalBase;
char c;
if (temp < 10)
{
c = temp + '0';
s1 += c;
}
else
{
c = temp - 10 + 'A';
s1 += c;
}
}
for (int i = s1.length() - 1; i >= 0; i--)
{
cout << s1[i];
}
cout << endl << endl;
}
Sorry, but I'm having issues understanding your code, so I thought I'd simplify it.
Here's the algorithm / code (untested):
void convert_to_base(const std::string& original_value,
unsigned int original_base,
std::string& final_value_str,
unsigned int final_base)
{
static const std::string digit_str =
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
if ((original_base > digit_str.length()) || (final_base > digit_str.length())
{
std::cerr << "Base value exceeds limit of " << digit_str.length() << ".\n";
return;
}
// Parse string from right to left, smallest value to largest.
// Convert to decimal.
unsigned int original_number = 0;
unsigned int digit_value = 0;
int index = 0;
for (index = original_value.length(); index > 0; --index)
{
std::string::size_type posn = digit_str.find(original_value[index];
if (posn == std::string::npos)
{
cerr << "unsupported digit encountered: " << original_value[index] << ".\n";
return;
}
digit_value = posn;
original_number = original_number * original_base + digit_value;
}
// Convert to a string of digits in the final base.
while (original_number != 0)
{
digit_value = original_number % final_base;
final_value_str.insert(0, 1, digit_str[digit_value]);
original_number = original_number / final_base;
}
}
*Warning: code not tested via compiler.**