/* strlen
* function returns the length of s.
* take care to return 0 if s is NULL
* or if s is of length 0
* you may not call an functions in your function
* int strlen (string s);
* Get string s
* Loop through s array
* if s[i] == \0, return 0
* else
* increment counter
*/
#include <cstdio>
#include <string>
#include <iostream>
usingnamespace std;
// function prototype
int strlen(string s);
int main(void)
{
// Get string s
string str;
printf_s("Please give me a string of characters: ");
do
{
cin >> str;
}
while (str[0] == '\0');
// pass s to function to determine length
int x = strlen(str);
printf_s("The length of s = %i\n", x);
}
int strlen(string s)
{
// initialize counter i to zero
int i = 0;
do
{
if (s[i] == '\0')
{
return 0;
}
else
{
i++;
}
}
while (s[i] != '\0');
return i;
}
What version of C++ are you using?
C++98: Accessing the value at data()+size() produces undefined behavior: There are no guarantees that a null character terminates the character sequence pointed by the value returned by this function. See string::c_str for a function that provides such guarantee. http://www.cplusplus.com/reference/string/string/data/
I read my problem wrong. Instead of re-prompting the user, I need to return a zero if s is NULL. I would like to let the user know that the string length is zero.
/* strlen
* function returns the length of s.
* take care to return 0 if s is NULL
* or if s is of length 0
* you may not call any functions in your function
* int strlen (string s);
* Get string s
* Loop through s array
* if s[i] == \0, return 0
* else
* increment counter
*/
#include <cstdio>
#include <string>
#include <iostream>
usingnamespace std;
// function prototype
int strlen(string s);
int main(void)
{
// Get string s
string str;
printf_s("Please give me a string of characters: ");
getline(cin, str);
if (str[0] != NULL)
{
// pass s to function to determine length
int x = strlen(str);
printf_s("The length of s = %i\n", x);
}
else
{
printf_s("The string length is 0!\n");
}
}
int strlen(string s)
{
// initialize counter i to zero
int count = 0;
while(s[count] != '\0')
{
count = count + 1;
printf_s("The count is: %i\n", count);
}
return count;
}