Empty string increasing size by one in C++ -
the following code snippets output different results same input (7747774):
a:
#include <iostream> #include <string> #include <algorithm> using namespace std; int main() { string n; cin >> n; int k = count(n.begin(), n.end(), '4') + count(n.begin(), n.end(), '7'); string c = to_string(k); bool lucky = (k>0) && (count(c.begin(), c.end(), '4') + count(c.begin(), c.end(), '7') == c.size()); cout << (lucky?"yes":"no") << endl; return 0; } b:
#include <iostream> #include <string> #include <algorithm> using namespace std; int main() { string n; cin >> n; int k = count(n.begin(), n.end(), '4') + count(n.begin(), n.end(), '7'); string c = "" + k; bool lucky = (k>0) && (count(c.begin(), c.end(), '4') + count(c.begin(), c.end(), '7') == c.size()); cout << (lucky?"yes":"no") << endl; return 0; } a prints yes, while b prints no, size of 'c' in b has increased one. why that?
string c = "" + k; doesn't think does. think equivalent std::to_string(k), no. actually increment pointer of string literal "" k.
that's undefined behavior (as k not 0 - wouldn't change pointer), , can result. have use std::to_string or std::atoi or similar functions.
Comments
Post a Comment