c++ - Alternative Characters - HackerRank -
i beginner, alternative code welcomed. program crashes after inputing values. want know more problem, since have seen many time.
#include<cstdio> #include<vector> #include<iostream> #include<string> using namespace std; int main() { vector<string> str; int n,i=0,count=0,a=0,b=1; string j; cin >> n; while(i<n) { cin >> j; str.push_back(j); i++; } for(i=0;i<n;i++) { while(b!='\0') { if(str[i][a] == str[i][b]) { count++; } a++; b++; } } cout << count; return 0; }
in order strange program work should 3 things: set init values a
, b
on every external loop step; change b!='\0'
condition str[i].c_str()[b]!='\0'
in order check not b
, string literal; call string::c_str()
method on strings, because not guaranteed string null-terminated, c-style strings stand condition.
for(i=0;i<n;i++) { = 0; b = 1; while(str[i].c_str()[b]!='\0') { if(str[i].c_str()[a] == str[i].c_str()[b]) { count++; } a++; b++; } }
Comments
Post a Comment