c++ - Adding null character after string computation -
i trying print string "ans" directly using
cout << ans;
instead of going through loop on each character of string. here complete code have written (string ans
, s
have same size).
ps: program takes string , print corresponding number associated character of mobile keypad.(like b c give 2, d e f give 3)
(so string abcdef
print 222333
why string ans
, s
have same size)
ps: have written in comments problem is.
#include<iostream> char has[]={'2','2','2','3','3','3','4','4','4','5','5','5','6','6','6','7','7','7','7','8','8','8','9','9','9','9'}; using namespace std; int main() { //code int t; cin>>t; while(t) { string s,ans; int i; cin>>s; for(i=0;i<s.length();i++) { ans[i]=has[s[i]-'a']; } ans[i]='\0'; cout<<ans; // **does not printing string "ans" why?**** for(i=0;i<s.length();i++) cout<<ans[i]; // **printing string "ans" using loop** cout<<endl; //**some other methods found in forum commented them** //string str(ans); //cout<<str.c_str(); t--; } return 0; }
a std::string
initialized empty string. accessing ans
via operator[]
, not add characters string. accessing non-existing indices way undefined behaviour, unfortunately didn't cause crash hint error.
possible solutions: initialize string needed length if want keep on using operator[]
or use std::stringstream
form needed string.
btw: std::string
doesn't need terminating nul-character.
Comments
Post a Comment