#include #include // Try running this code with various inputs. // Is it working correctly, or is there a bug? // // Once you get it working, try entering the // strings // // HI // // and // // Hi! // // - What are their lengths? // - Why? // Function declarations std::size_t length( char const str[] ); int main(); // Function definitions int main() { char str[1000]; for ( std::size_t n{ 0 }; n < 4; ++n ) { // std::cin reads characters up to the first // whitespace character, such as a space (' '), // newline ('\n'), or tab ('\t'). std::cout << "Enter a string: "; std::cin >> str; std::cout << "The string you entered was \"" << str << "\"." << std::endl; std::cout << "The length of your string is " << length( str ) << "." << std::endl; } return 0; } // Calculate the length of a string. std::size_t length( char const str[] ) { std::size_t len{ 0 }; while ( str[len] != '0' ) { ++len; } return len; } // The bug is in the comparison. // // The character '0' is the digit zero. It is an // ordinary character that could appear in a string // such as // // "ECE150" // // In ASCII, the character '0' is represented by // // 00110000 // // while '1' is represented by // // 00110001 // // and '2' by // // 00110010 // // and so on. // // A C-style string, however, ends with the null // character '\0'. In ASCII, the null character is // // 00000000 // // Thus, the loop should be // // while ( str[len] != '\0' ) { // ++len; // } // // For example, the string // // "Hi!" // // is stored as four characters: // // 'H' 'i' '!' '\0' // // Its length is 3 because the null character marks // the end of the string and is not part of its length. // Here is the corrected function: /* std::size_t length( char const str[] ) { std::size_t len{ 0 }; while ( str[len] != '\0' ) { ++len; } return len; } */