Invalid String initialization for c++ - c++

I was trying to make a script for a math thing that a saw and I got the following error...
line 23|error: invalid initialization of non-const reference of type 'std::__cxx11::string&' {aka 'std::__cxx11::basic_string&'} from an rvalue of type 'bool'|
I am pretty new to c++ and I tried to search this problem on the internet, but nothing works. Can you please help me?? (code below btw)
#include <string>
#include <math.h>
using namespace std;
bool hasEnding (std::string &fullString, std::string &ending) {
if (fullString.length() >= ending.length()) {
return (0 == fullString.compare (fullString.length() - ending.length(), ending.length(), ending));
} else {
return false;
}
}
int main() {
int current_num;
bool odd;
bool even;
cout << "Type a positive number: "; // Type a number and press enter
cin >> current_num;
while (current_num >= 2) {
std::string s = std::to_string(current_num);
cout << s << endl;
odd = hasEnding (s, "1"||"3"||"5"||"7"||"9");
even = hasEnding (s, "0"||"2"||"4"||"6"||"8");
if (odd == true) {
current_num = current_num*3;
current_num = current_num+1;
}
if (even == true) {
current_num = current_num/2;
}
}
return 0;
}

Thanks to the people in the comments... I fixed it by finding a thing that checks if a number in even or odd instead of making a very inefficient script which checks the last number. The solution for it was n % 2 == 0

Related

I Want This Code To Prove If An Integer Is A Palindrome. How Do I do It?

I am sure this code isn't perfect, but I am new to programming and am trying to work out a challenge for checking if a number is a palindrome or not. I tried writing a bool-type function in the code to return 'true' if the number is a palindrome and 'false' otherwise.
Anyway, jumping to context, I want this code to print 'YES" every time the computer notices a sign of palindrome-ism. The code is compiling successfully, however, it does not output anything after 'What is the integer you wanna check palindromism for?:' even when inputting numbers like '12321', '111', '1234321' (palindromes).
Can anyone help me, and if possible, without changing much of the code tell me ways to achieve what I want to (to prove palindrome-ism)?
#include <cstring>
using namespace std;
bool isPalindrome(int x, string md) {
int y = md.length() + 1;
char abz[y];
for (int i=0; i < md.length()-1; ++i) {
if (abz[i] == (md.length()-1)-i){
cout << "YES";
}
}
return true;
}
int main(){
int x;
cout << "What is the integer you wanna check palindromism for?: ";
cin >> x;
string md = to_string(x);
isPalindrome(x, md);
return 0;
}
Thanks!
I'm not sure what you're trying to do in isPalindrome.
One way to check if a string of size len is palindrome is to compare its i-th and (len-i-1)-th characters for i ranging in [0, len / 2).
If they differ at any point the string is not palindrome.
Here's how you may do it:
bool isPalindrome(std::string const& md) {
if (md.empty()) // Empty strings are not palindrome
return false;
auto const len = md.size();
auto const halfLen = len / 2;
for (std::size_t i = 0; i != halfLen; ++i)
if (md[i] != md[len - i - 1])
return false;
return true;
}
Can anyone help me, and if possible, without changing much of the code tell
me ways to achieve what I want to (to prove palindrome-ism)?
Please check the comments I've added in the code:
// Include the correct headers
#include <iostream>
#include <string>
// Don't do this
//using namespace std;
// This just checks if the string is palindrome.
// It does not print anything.
bool isPalindrome(std::string const& md) {
if (md.empty())
return false;
auto const len = md.size();
auto const halfLen = len / 2;
for (std::size_t i = 0; i != halfLen; ++i)
if (md[i] != md[len - i - 1])
return false;
return true;
}
int main() {
// No need to parse the number and convert it to string again.
//int x;
std::string md;
std::cout << "What is the integer you wanna check palindromism for?: ";
// NOTE: you may input any string here: not just integers.
std::cin >> md;
std::cout << (isPalindrome(md) ? "YES" : "") << '\n';
// ^ print "YES" or nothing
return 0;
}
You may also implement isPalindrome with algorithms and iterators like so:
// You'll need these two headers
#include <algorithm>
#include <iterator>
template <typename BidIt>
bool isPalindrome(BidIt first, BidIt last) {
if (first == last)
return false;
auto const halfLength = std::distance(first, last);
auto const mid = std::next(first, halfLength);
auto const rFirst = std::make_reverse_iterator(last);
return std::equal(first, mid, rFirst);
}
bool isPalindrome(std::string const& str) {
return isPalindrome(std::cbegin(str), std::cend(str));
}
This is basically the same algorithm as above but you can reuse
template <typename BidIt>
bool isPalindrome(BidIt, BidIt);
with more containers than just std::string.

Check if a string is a number without regex or try catch

I want to implement a simple is_number function that checks if it's an integer, float or an unsigned long int using this method:
bool isNumber(const std::string& str)
{
size_t idx = 0;
//Check if it's an integer
std::stoi(str,&idx);
if (idx == str.size())
return true;
//Check if it's a float
std::stof(str,&idx);
if (idx == str.size() || str[str.size()-1] == 'f' && idx == str.size()) //Cause I do have some float numbers ending with 'f' in the database
return true;
//Check if it's an unsigned long int
std::stoul(str,&idx);
if (idx == str.size())
return true;
return false;
}
But if I test it with a pure string like "test" or "nan", it will throw an error because I'm trying to change a pure string to an integer.
terminate called after throwing an instance of 'std::invalid_argument'
what(): stoi
However if I test it with "0nan" for example, stoi or the others will retrieve the first number and assign the index position of the first found number to the idx variable.
Is it possible to find a workaround for pure strings like "nan" or any other?
Or is there a better method to implement this without regex or try-catch?
std::stoi throws when it fails. Instead of using C i/o you can use C++ streams, try to read from the stream and check if there is something left in the stream:
#include <string>
#include <sstream>
#include <iostream>
enum Number {Float,Signed,Unsigned,NotANumber};
template <typename T>
bool is_only_a(const std::string& str){
std::stringstream ss(str);
T x;
return (ss >> x && ss.rdbuf()->in_avail() ==0);
}
Number isNumber(const std::string& str)
{
size_t idx = 0;
if (is_only_a<unsigned long>(str)) return Unsigned;
else if (is_only_a<int>(str)) return Signed;
else if (is_only_a<float>(str)) return Float;
return NotANumber;
}
int main() {
std::cout << isNumber("1.2") << "\n";
std::cout << isNumber("12") << "\n";
std::cout << isNumber("-12") << "\n";
std::cout << isNumber("asd") << "\n";
std::cout << isNumber("nan") << "\n";
}
Order is important, because 12 could be a float as well.
The link I posted in the comments is most probably what you need.
The only slight modification needed from the answers there is adding a +/- sign, and an optional (at most one) decimal point:
bool isNumber(const std::string &s) {
bool first_char = true;
bool saw_decpt = false;
for (const auto &it: s) {
if (std::isdigit(it)) { first_char = false; }
else if (it == '+' && first_char) { first_char = false; }
else if (it == '-' && first_char) { first_char = false; }
else if (it == '.' && !saw_decpt) { first_char = false; saw_decpt = true; }
else return false;
}
return true;
}

Check if every string in a set contains equal number of 'a' and 'b' okay I tried again will some one work something out now?

Will some one explain or make a program in c++ of this for me? Got assignment but don't know how to do it.
Question: You are given a set of strings which contain only as and bs, your program should be able to check whether each string has the same number of as and bs in it or not.
e.g. The program will respond true if it get {ab, aabb, aaabbbb, bbbaaa} and say false when it gets {aab, bbba, aaabbbb}
Solve it using stack
#include <iostream>
#include <string>
#include <stack>
#include <algorithm>
using namespace std;
int count1 = 0;
int count2 = 0;
bool isInLanguageL (string w);
int main()
{
string input;
cout << "Input any string; ";
getline(cin,input);
if (input.length() % 2 != 0)
cout <<"Pattern entered does not match the language ";
else
isInLanguageL(input);
return 0;
}
bool isInLanguageL (string w)
{
stack<string> word1, word2;
string a, b;
for (unsigned i = 0; i < w.length()/2; i++)
{
a = w.at(i);
word1.push(a);
}
reverse(w.begin(), w.end());
for (unsigned i = 0; i < w.length()/2; i++)
{
b = w.at(i);
word2.push(b);
}
while(!word1.empty() && !word2.empty())
{
word1.pop();
count1 = count1++;
word2.pop();
count2 = count2++;
}
if(count1 == count2)
return true;
else
return false;
}
This solution is using stack, please refer to the comments written in the code. If you have any doubt you can comment them.
Code:
#include <iostream>
#include <stack>
#include <string>
using namespace std;
void checkString(string s) {
if (s.size() % 2 != 0) {
cout << "Doesn't satisfy the conditon\n";
return;
}
stack<char> st;
int n = s.size();
for (int i = 0; i < n; ++i) {
/*
case - 1 : If the stack is empty you can directly push the current character into the stack
case - 2 : If there are elements present in the stack, then if the current character is equal to the top character on the stack then we can push the current character
beacuse we didn't find any new character to match them.
*/
if (st.empty() || (st.top() == s[i])) {
st.push(s[i]);
}
/*
case-3 : If the stack is not emtpy and current character is different from the top character on the stack then we found a match like a-b (OR) b-a, so then we will
remove the top element from the stack and move to next character of the string
*/
else if (st.top() != s[i]) {
st.pop();
}
}
/*
case - 1 : After iterating through all the characters in the string, if we find the stack is emtpy then we can say all characters are not matched
case - 2 : If stack is emtpy, then that means all the characters are matched.
*/
(st.empty()) ? (cout << "Yes, satisfies the conditon\n") : (cout << "Doesn't satisfy the conditon\n");
}
int main() {
string s = "";
cin >> s;
checkString(s);
return 0;
}
Your solution has a number of mistakes that you should probably solve by using a debugger. Here's a reference.
This solution doesn't use a stack as you asked for, but you can write this function that uses algorithms to solve your problem:
namespace rs = std::ranges;
bool all_equal_as_and_bs(auto const & strings)
{
return rs::all_of(strings, [](auto const & string)
{
return rs::count(string, 'a') == rs::count(string, 'b');
});
}
And use it like this:
all_equal_as_and_bs(std::vector<std::string>{"ab", "aabb", "aaabbb", "bbbaaa"}); // true
all_equal_as_and_bs(std::vector<std::string>{"aab", "bba", "aaabbbb", "bbbaaa"}); // false

Quick Assistance involving char's and if statements

Sorry if this is REALLY trivial, I'm just sick at being stuck at step one and need to continue and I have no help anywhere else. I can not for the life of me get this function to cooperate with me. Here's the source:
#include <iostream>
using namespace std;
void ReadDials(){
};
void ToDigit(char *x){
if (*x = 'a'){*x = '54';}
else if (*x = 'A'){*x = 2;}
else if (*x = 'b'){*x = 3;}
else(*x = 4);
};
int main()
{
char one;
char two;
char three;
cin >> one;
ToDigit(&one);
cout << "one is: " << one << endl;
system("PAUSE");
}
What I've tried: alternating between the actual number 2 and the ascii pointer of 2 which I believe is '32' I've used == to try, I've done everything I can possibly think of and I know I'm over thinking it. The point is to have that function convert user input into numbers for a phone dialer.
Problems ranging from numbers not syncing with if statements, and seeing a ':D' face on the console. It's making me very annoyed.
If I need to make myself more clear, I'll be more than happy too.
Thanks in advance for any assistance.
In if (*x = 'a'), the = is an assignment. You want == for comparison. Also, '54' isn't a character value.
void ToDigit(char *x){
if (*x == 'a') { *x = '54'; } /* what is this supposed to do? */
else if (*x == 'A') {*x = 2; }
else if (*x == 'b') {*x = 3; }
else { *x = 4 };
};
It looks like you are trying to use x as an input and output. Let's step back a minute. Let's instead write a function that takes a single char and returns an integer. This would be the canonical way of taking a char and getting a number from it.
int ToDigit(char x){
if (x == 'a') { return 54; }
if (x == 'A') { return 2; }
if (x == 'b') { return 3; }
return 4 ;
};
To use this form of the function, you'd assign the return value to a variable of type int in this case.
char my_input;
int mapped_number;
std::cin >> my_input;
mapped_number = ToDigit(my_input);
std::cout << my_input << " maps to " << mapped_number << ".\n";

string!! allow letter only for the first character of my rectangle names

I can't get the right output.. please help me..
and it should return false when I put number as the first character for the name
like this ,
Enter the name of the first rectangle: rec 1a
Invalid input. Type 'rec' following by the name or 'stop' if done.
Try again! Enter the name of the first rectangle: rec a
Enter a's bottom left x and y coords: 9 3
Enter a's length and height: 2 8
i am only allow to use these 3, not anything else..
#include <iostream>
#include <string>
#include <vector>
and my code is
bool promptread_rec(const string & prompt, const string & invalid, const string & usedname, string & input, vector<Rectangle> & list)
{
cout << prompt;
getline(cin, input);
if (input == "stop")
{
return true;
}
else if (input.substr(0,4) != "rec ")
{
cout << invalid << endl;
return false;
}
else if (input[4] == '0' || input [4] == '1' || ......)
{
cout << invalid << endl;
return false;
}
else if (list.size() > 0)
{
for (int i = 0; i < list.size(); i++)
{
if (input == list[i].getName())
{
cout << usedname;
return false;
}
}
return true;
}
else
{
return true;
}
}
is there a faster way to do it?? need to avoid all numbers e.g. 0,1,2,3,...,9
From the header cctype, you may use the function isalpha(c) on the first character of the string, like:
string a = "a1234";
assert(isalpha(a.at(0)) == true);
a = "1234";
assert(isalpha(a.at(0)) == true);
Just remember to access a.at(0) only if the string is not empty or else it will throw a std::out_of_range exception
References:
http://www.cplusplus.com/reference/cctype/isalpha/
http://www.cplusplus.com/reference/cassert/assert/
http://www.cplusplus.com/reference/string/string/at/
Since you cannot use any other headers you have to implement your own functions, which is actually simple enough for ASCII characters:
bool IsLetter(char c) {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
bool IsDigit(char c) {
return c >= '0' && c <= '9';
}
Using these two helper functions you can write a function to test if a name is valid:
bool IsValidName(const std::string &name);
I leave this for you to implement.