Problem | std::string length gives Junk value in expression

Discussion in 'C++' started by Pradeep, Dec 20, 2007.

  1. Pradeep

    Pradeep Guest

    Hi All,

    I am facing an issue where length method of std::string class gives a
    junk value when used in a expression.

    Here's an example. The code should not go into the for loop but it
    does because the value of j-str.length comes out to be some junk value

    int j = 12;
    std::string
    str("0123456789012"); //
    of length 13
    std::cout << "str length" << str.length() <<
    std::endl; // gives 13
    std::cout << " j - str.length" << (j- (str.length())) <<
    std::endl; // gives junk value
    for(int i=0; i < j - str.length() ;i+
    +) // so it goes
    inside the loop
    //
    while it should not for 12-13
    //
    = -1
    {
    std::cout << "Show hte problem" << std::endl;
    }


    However it starts to work if instead of the expresssion I use a
    variable
    int x = j - str.length.

    Can somebody help me out and tell me the reason for this.

    Thanks in advance,
    Pradeep
    Pradeep, Dec 20, 2007
    #1
    1. Advertising

  2. Pradeep

    Tim Love Guest

    Pradeep <> writes:

    >Hi All,


    >I am facing an issue where length method of std::string class gives a
    >junk value when used in a expression.

    string isn't the problem. Try this

    #include <iostream>
    int main() {
    unsigned int k=13;
    int j = 12;
    std::cout << "12 - 13 =" << j - k << std::endl;;
    }

    and have a look at what length() returns.
    Tim Love, Dec 20, 2007
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Sam
    Replies:
    3
    Views:
    14,081
    Karl Seguin
    Feb 17, 2005
  2. Peter Jansson
    Replies:
    5
    Views:
    6,275
    Ivan Vecerina
    Mar 17, 2005
  3. Replies:
    5
    Views:
    656
    John W. Kennedy
    Jan 11, 2007
  4. Fei Liu
    Replies:
    9
    Views:
    435
  5. Jeffrey Walton
    Replies:
    10
    Views:
    929
    Mathias Gaunard
    Nov 26, 2006
Loading...

Share This Page