c++ unable to get proper string input -
i new programming wrote simple function calculate length of string unable take input string user properly(have tried alternatives).
/////////function calculate length of string//////////////////// void str_length(){ char str[30]; int counter=0; cout << "enter string: "; gets(str); //cin.getline(str,256); //cin >> str; for(int i=0;str[i] != '\0';i++){ counter++; } cout << "string length is: " << counter << endl; } ///////////////////////////////////////////////////////////////
of possible ways program either exits abruptly or 'cin' can partial string till first space.
if tried cin.getline(str,256)
, you'd have needed buffer declared char str[256]
.
you shouldn't involving these things however. stick std::string
:
std::string str; // declare string std::getline(std::cin, str); // line std::cin stream , put in str unsigned int stringlength = str.length(); // length of string
Comments
Post a Comment