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

P

Pradeep

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
 
T

Tim Love

Pradeep said:
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.
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,905
Latest member
Kristy_Poole

Latest Threads

Top