简体   繁体   中英

How do I use strlen() as int?

I want to use the numbers that strlen() returns in a function that requires an int value.

functionName((strlen(word)+strlen(otherWord)+1));

This piece of code doesn't work because they return size_t.

Is there any way to convert that result to int so I can make addition operations and use them as int?

其他大多数答案都使用C风格的强制转换,您不应该在C ++中执行:您应该使用static cast

functionName( static_cast<int>((strlen(word)+strlen(otherWord)+1));

First you need to check if you can add the values, then you need to check if you can cast to int, and the you cast..

sizt_t size = strlen(word);
if (std::numeric_limits<size_t>::max()-size >= strlen(otherword))
{
    size += strlen(otherword);
    if (std::numeric_limits<size_t>::max()-size >= 1))
    {
        size += 1;
        if (size <= std::numeric_limits<int>::max())
        {
            functionName(int(size));
        }
        else
        {
            //failed
        }
    }
    else
    {
        //failed
    }
}
else
{
     //failed
}

Unless you have veeery long strings here it is safe to use cast:

functionName((int)(strlen(word)+strlen(otherWord)+1));

if you want you can use static_cast<int> but there is no differences now.

functionName(static_cast<int>(strlen(word)+strlen(otherWord)+1));

size_t is internally unsigned int on most sensible platforms. Typecast it to int and be done with it:

functionName(static_cast<int>((strlen(word)+strlen(otherWord)+1));

or C-style (which is discouraged but legal):

functionName((int)((strlen(word)+strlen(otherWord)+1));

How likely is it that the sum total of those lengths would be over 0x7fffffff (that's the limit of int on 32-bit platforms)? Probably not very likely.

This piece of code does work, unless your compiler does something very strange or you haven't shown us the actual code.

The only thing that could possibly go wrong is an overflow error (unsigned ints can hold larger values than signed ints). You could check that with std::numeric_limits<int> if you really think your strings can become that incredibly large.

In C++ use otherWord.length() : functionName( word.length() + otherWord.length() ) .

This is one way to do a strlen() of functionName((int)(strlen(word)+strlen(otherWord)+1)); .

#include <iostream>
#include <string>
using namespace std;

int functionName(int rstr )
{
    return rstr;
}




int main ()
{
    char word[]      = "aaa";
    char otherWord[] = "bbb";

    cout<< "word =  "<<word<<"\n" ;
    cout<< "otherWord =  "<<otherWord<<"\n" ; 

    cout<<  "The sentence entered is   "<<  functionName((int)(strlen(word)+strlen(otherWord) ))<<"   characters long \n\n";

  return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM