Domanda

I try to get the position of the string "-a" with this code

#include <iostream>
#include <string>

using namespace std;

int main(void)
{
string command("test –a string");
size_t pos = command.find("-a");
cout << "position found = " << pos << endl;
}

this produce this output:

position found = 4294967295

If I remove the '-' it's work as expected. 8 is returned.

È stato utile?

Soluzione

You get the string::npos value returned, because the library thinks that it cannot find -a in the string.

The reason for this is that you use different dashes a long dash in the string and a short dash - in the search string.

Once you replace the character with the correct one in both places, your code starts working fine (demo).

Altri suggerimenti

It means that there are different the first characters.

You can check this using the first characters and placing them in statement

std::cout << ( '–' == '-' ) << std::endl; 

As they are different function find returns value std::string::npos that is defined as std::string::size_type( -1 ) or equal to 4294967295

If you look really close you will find the '–' is no '-'.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top