Thread: Get length of string as integer

  1. #1
    Registered User
    Join Date
    Nov 2004
    Posts
    6

    Get length of string as integer

    I have an input file that has data in for format:
    1 asdfhboais
    so its an integer followed by a group of characters. I need to figure out how many characters there are. Then access them one at a time to compare them. I tried to save them to a string and check, like so:
    Code:
    int number, len;
    string letters;
    cin >> number >> letters;
    len = letters.length();
    but I get a warning because the string.length() function returns an unsigned integer. I need to use the length later as an int. Is there a good way to do what I need. Thanks!

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    Use size_t or an unsigned int, or just ignore the warning. Converting from unsigned int to signed int only matters if the value is greater than the largest positive value that a signed int can hold, and that almost certainly will not be the case if you are counting letters like that. If you don't want the warning you can cast the result to a regular int:

    len = static_cast<int>(letters.length());

  3. #3
    Registered User
    Join Date
    Nov 2004
    Posts
    6
    wow that was super fast. Thanks!
    static_cast, I knew I forgot something important.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Assignment HELP!!
    By cprogrammer22 in forum C Programming
    Replies: 35
    Last Post: 01-24-2009, 02:24 PM
  2. Lame null append cause buffer to crash
    By cmoo in forum C Programming
    Replies: 8
    Last Post: 12-29-2008, 03:27 AM
  3. Find String length and Arraysearch
    By s.rajaram in forum C Programming
    Replies: 5
    Last Post: 10-03-2007, 02:28 AM
  4. Compile Error that i dont understand
    By bobthebullet990 in forum C++ Programming
    Replies: 5
    Last Post: 05-05-2006, 09:19 AM
  5. Replies: 4
    Last Post: 03-03-2006, 02:11 AM