not able to compare count function used on strings in c++? - c++

here is the code :
#include <iostream>
#include <ostream>
#include <bits/stdc++.h>
#include <string>
int main(){
std::string num {"hello"};
std::string num1 {"hii"};
int nums = std::count(num.begin(),num.end(),num[0]);
int nums1 = std::count(num1.begin(),num1.end(),num1[0]);
std::cout << std::count(num1.begin(),num1.end(),num1[0] ) == count(num.begin(),num.end(),num[0]);
std::cout << nums == nums1 ;
return 0;
}
please help if anyone know problem. updated......

To use == in operator << we need to add parentheses here since overloaded operator << has higher precedence than comparison operator. If you use a mordern compiler, it will give you detailed hints, such as clang 11 will give use such warnings:
warning: overloaded operator << has higher precedence than comparison operator [-Woverloaded-shift-op-parentheses]
Then we can fix it as:
#include <algorithm>
#include <iostream>
#include <ostream>
#include <string>
int main() {
std::string num{"hello"};
std::string num1{"hii"};
std::size_t nums = std::count(num.begin(), num.end(), num[0]);
std::size_t nums1 = std::count(num1.begin(), num1.end(), num1[0]);
std::cout << (std::count(num1.begin(), num1.end(), num1[0]) ==
count(num.begin(), num.end(), num[0]));
std::cout << (nums == nums1);
return 0;
}
Online demo

Related

How could/should I print text strings above number columns in C++?

I would like to print the strings at the top of columns with a 1 x 3 array.
I have edited this simple function several times, and this produces the least errors. New to C++, reading Deital Chap 6 Recursive.
What am I missing? I started with half brackes around strings, and brackets seemed to produce less errors.
Here is the code:
#include <iostream>
#include <string>
#include <array>
using namespace std;
int main() {
array a[1][3] = ["Car" "Hours" "Charge"]
cout<< a << endl;
}
Terminal produces errors as such:
parking_charges_6_12.cpp: In function ‘int main()’:
parking_charges_6_12.cpp:8:7: error: missing template arguments before ‘a’
8 | array a[1][3] = ["Car" "Hours" "Charge"]
^
This should work:
#include <array>
#include <iostream>
#include <string>
int main(){
std::array<std::string, 3> headlines = {"Car", "Hours", "Charge"};
for( auto const& elem : headlines ){
std::cout << elem << "\t";
}
}
It should be curly braces {} in the initializer, not []. And you need a comma between each element.
On the other hand, in later C++ revisions array can detect the type and number of elements, so you don't have to give that.
#include <iostream>
#include <array>
using namespace std;
int main() {
array a = {"Car", "Hours", "Charge"};
for (auto& item : a)
cout<< item << endl;
}
How about something like this:
#include<iostream>
using namespace std;
int main() {
string data[3] = {"Car", "Hours", "Charge"};
for (int i = 0; i < 3; i++)
cout << data[i] << " ";
}
Obviously it is not using the array header, but it's a working example. If you do need to use the array header, you can try something like :
#include <array>
#include <iostream>
#include <iterator>
#include <string>
using namespace std;
int main() {
array<string, 3> ar3 = {"Car", "Hours", "Charge"};
cout << ar3.size() << endl;
for (auto i : ar3)
cout << i << ' ';
return 0;
}
You can see it working online here

Build incremental std::string

I try to build an std::string in the form of "start:Pdc1;Pdc2;Pdc3;"
With following code I can build the repeated "Pdc" and the incremental string "123" but I'm unable to combine the two strings.
#include <string>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <iterator>
#include <numeric>
int main()
{
std::ostringstream ss;
std::string hdr("start:");
std::fill_n(std::ostream_iterator<std::string>(ss), 3, "Pdc;");
hdr.append(ss.str());
std::string v("abc");
std::iota(v.begin(), v.end(), '1');
std::cout << hdr << std::endl;
std::cout << v << std::endl;
std::cout << "Expected output: start:Pdc1;Pdc2;Pdc3;" << std::endl;
return 0;
}
How can I build this string? Preferable without a while or for loop.
The expected output is: start:Pdc1;Pdc2;Pdc3;
std::strings can be concatenated via their operator+ (or +=) and integers can be converted via std::to_string:
std::string res("start:");
for (int i=0;i<3;++i){
res += "Pdc" + std::to_string(i+1) + ";";
}
std::cout << res << "\n";
If you like you can use an algorithm instead of the handwritten loop, but it will still be a loop (your code has 2 loops, but only 1 is needed).
Code to generate your expected string, though with a small for loop.
#include <iostream>
#include <string>
#include <sstream>
std::string cmd(const std::size_t N)
{
std::ostringstream os;
os << "start:";
for(std::size_t n = 1; n <= N; ++n) os << "Pdc" << n << ";";
return os.str();
}
int main()
{
std::cout << cmd(3ul);
return 0;
}

How can I replace multiple characters with just one (C++)?

We have a char. We need to replace all ab characters from our char with the letter c.
Example we have :
abracadabra
the output will be :
cracadcra
I tried to use replace() function from C++, but no success.
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
string test;
cin>>test;
for(int i=0;i<(strlen(test)-1);i++)
{
if((test[i]=='a')&&(test[i+1]=='b')){
test.replace( test[i], 'c' );
test.replace( test[i+1] , ' ' );
}
}
cout << test << endl;
return 0;
}enter code here
You can use C++11 regex:
#include <iostream>
#include <regex>
#include <string>
int main() {
std::string str = "abracadabra";
std::regex r("ab");
std::cout << std::regex_replace(str, r, "c") << "\n"; // cracadcra
}
Problem:
That is not the syntax of std::string::replace.
Solution:
As is mentioned here the syntax is std::string::replace(size_t pos, size_t len, const string& str). Do test.replace(i, 2, "c" ) instead of test.replace(test[i],'c').
Or use regular expressions as dtell pointed.
Adittional information:
using namespace std; is considered a bad practice (More info here).
You should use std::string::size instead of strlen when you're working with std::string.
To work with std::string you should use #include <string> instead of #include <cstring>.
Full code:
#include <iostream>
int main()
{
std::string test;
std::cin >> test;
for(unsigned int i = 0; i < test.size() - 1; i++)
{
if((test[i]=='a') && (test[i+1]=='b'))
{
test.replace(i, 2, "c" );
}
}
std::cout << test << std::endl;
return 0;
}
The simplest thing you can do by using the standard library is first to find ab and then replace it. The example code I wrote is finding string ab unless there is None in the string and replacing it with c.
#include <iostream>
#include <string>
int main()
{
std::string s = "abracadabra";
int pos = -1;
while ((pos = s.find("ab")) != -1)//finding the position of ab
s.replace(pos, sizeof("ab") - 1, "c");//replace ab with c
std::cout << s << std::endl;
return 0;
}
//OUTPUT
cracadcra

Vectors and Strings C++

#include <vector>
#include <iostream>
#include <cstring>
#include <string.h>
using namespace std;
int main()
{
vector<string> test;
test.push_back("yasir");
test.push_back("javed");
for(int i=0; i!=test.end();i++)
{
cout << test[i];
}
}
Why is this code giving up an error? I am unable to identify the cause of the error.
Error: No Match for operator !=....
First of all, you are trying to compare int with the iterator of vector.
for(int i=0; i!=test.end();i++)
{
cout << test[i];
}
Here, the test.end() returns the iterator. There is no overloaded operator!= which can compare integer (int i = 0) with that iterator (test.end()).
So your loop should look more like:
for (std::vector<string>::iterator i = test.begin(); i != test.end(); i++)
{
cout << *i;
}
You can replace std::vector<string>::iterator with auto, if using C++11 or newer.
The next thing, you included <string.h> which contains old functions such as: strlen, strcpy. Similarly, <cstring> contains C-style strings.
If you want to you use operator<<, so if you want to write:cout << then you have to do: #include <string>.
As already mentioned, the problem is, that you try to compare an integer with an iterator in the "middle" of your for statement. Try this instead, it's more intuitive from my point of view
#include <vector>
#include <iostream>
#include <cstring>
#include <string.h>
using namespace std;
int main()
{
vector<string> test;
test.push_back("yasir");
test.push_back("javed");
for(int i=0; i<test.size();++i)
{
cout << test[i];
}
}

Lexical cast Partial conversion - Is it possible?

lexical_cast throws an exception in the following case. Is there a way to use lexical_cast and convert the string to integer.
#include <iostream>
#include "boost/lexical_cast.hpp"
#include <string>
int main()
{
std::string src = "124is";
int iNumber = boost::lexical_cast<int>(src);
std::cout << "After conversion " << iNumber << std::endl;
}
I understand, I can use atoi instead of boost::lexical_cast.
If I'm understanding your requirements correctly it seems as though removing the non-numeric elements from the string first before the lexical_cast will solve your problem. The approach I outline here makes use of the isdigit function which will return true if the given char is a digit from 0 to 9.
#include <iostream>
#include "boost/lexical_cast.hpp"
#include <string>
#include <algorithm>
#include <cctype> //for isdigit
struct is_not_digit{
bool operator()(char a) { return !isdigit(a); }
};
int main()
{
std::string src = "124is";
src.erase(std::remove_if(src.begin(),src.end(),is_not_digit()),src.end());
int iNumber = boost::lexical_cast<int>(src);
std::cout << "After conversion " << iNumber << std::endl;
}
The boost/lexical_cast uses stringstream to convert from string to other types,so you must make sure the string can be converted completely! or, it will throw the bad_lexical_cast exception,This is an example:
#include <boost/lexical_cast.hpp>
#include <iostream>
#include <string>
#define ERROR_LEXICAL_CAST 1
int main()
{
using boost::lexical_cast;
int a = 0;
double b = 0.0;
std::string s = "";
int e = 0;
try
{
// ----- string --> int
a = lexical_cast<int>("123");//good
b = lexical_cast<double>("123.12");//good
// -----double to string good
s = lexical_cast<std::string>("123456.7");
// ----- bad
e = lexical_cast<int>("abc");
}
catch(boost::bad_lexical_cast& e)
{
// bad lexical cast: source type value could not be interpreted as target
std::cout << e.what() << std::endl;
return ERROR_LEXICAL_CAST;
}
std::cout << a << std::endl; // cout:123
std::cout << b << std::endl; //cout:123.12
std::cout << s << std::endl; //cout:123456.7
return 0;
}