473,770 Members | 6,322 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

std::string, subscripting, and npos

std::string::np os is described in _TC++PL:SE_ (Section 20.3.4) as the
"all characters" marker. I tried to use it this way, but my program
crashes:

#include <iostream>
#include <string>

int main()
{
std::string s = "hi/hello/now";
std::cout << s << '\n';

for (std::string::s ize_type i = 0; i != std::string::np os; ++i) {
if (s[i] == '/') {
s[i] = '\\';
}
}

std::cout << s << '\n';
}
If I change "std::string::n pos" to "s.length() " then of course the
program works correctly. Why doesn't std::string::np os work in this
context?
--
Marcus Kwok
Jan 27 '06 #1
7 4869
On Fri, 27 Jan 2006 21:06:31 +0000 (UTC), ri******@gehenn om.net
(Marcus Kwok) wrote:
std::string::n pos is described in _TC++PL:SE_ (Section 20.3.4) as the
"all characters" marker. I tried to use it this way, but my program
crashes:

#include <iostream>
#include <string>

int main()
{
std::string s = "hi/hello/now";
std::cout << s << '\n';

for (std::string::s ize_type i = 0; i != std::string::np os; ++i) {
if (s[i] == '/') {
s[i] = '\\';
}
}

std::cout << s << '\n';
}
If I change "std::string::n pos" to "s.length() " then of course the
program works correctly. Why doesn't std::string::np os work in this
context?


std::string::np os is usually just an alias for ((unsigned)(-1)). You
are therefore incrementing i way past the end of the string's length.

std::string::np os is returned by most string functions which involve
some kind of find, and which would normally return the index or
position of the element being sought. Since there can never be such a
position, this value was chosen to indicate "not found" or not
present.

--
Bob Hairgrove
No**********@Ho me.com
Jan 27 '06 #2
Marcus Kwok wrote:
std::string::np os is described in _TC++PL:SE_ (Section 20.3.4) as the
"all characters" marker. I tried to use it this way, but my program
crashes:

#include <iostream>
#include <string>

int main()
{
std::string s = "hi/hello/now";
std::cout << s << '\n';

for (std::string::s ize_type i = 0; i != std::string::np os; ++i) {
if (s[i] == '/') {
s[i] = '\\';
}
}

std::cout << s << '\n';
}
If I change "std::string::n pos" to "s.length() " then of course the
program works correctly. Why doesn't std::string::np os work in this
context?


'npos' is a constant usually defined as (size_type)(-1). Its specific
purpose is to indicate "not found" condition when returning from 'find'
members and the "end" position when using 'substr'.

You mistakenly used it as if it is different for every 'string' object.
It's not. IIRC it's a static member.

V
Jan 27 '06 #3

"Marcus Kwok" <ri******@gehen nom.net> wrote in message
news:dr******** **@news-int2.gatech.edu ...
std::string::np os is described in _TC++PL:SE_ (Section 20.3.4) as the
"all characters" marker.
Its meaning depends upon context. It's most often used to
indicate 'not found' with e.g. 'find()'.
I tried to use it this way, but my program
crashes:

#include <iostream>
#include <string>

int main()
{
std::string s = "hi/hello/now";
std::cout << s << '\n';

for (std::string::s ize_type i = 0; i != std::string::np os; ++i) {
'npos' is not a valid index for a string. Even if you use the
meaning 'all characters', what would that value as an index
mean? The book doesn't say 'how many characters' does it? :-)
(and even if it did, then the highest valid index would be
'how many, less one' (because first index is 0).)

The valid index values are those integers in the set beginning with
zero and ending with 'string::size() - 1', inclusive.

'size() - 1' can never be equal to 'npos'. That's part of
'npos's definition. The value of 'npos' must be chosen by
an implementation to be some value that is *not* a valid
index. That's how e.g. 'find()' (which returns an index
value), can distinguish between a found element and 'not found'.

Once 'i's value passes 'size() - 1', using it as an index
will give undefined behavior. (The 'at()' member functinon
would throw an exception).

Write this instead:

for (std::string::s ize_type i = 0; i != s.size(); ++i) {
if (s[i] == '/') {
s[i] = '\\';
}
}

std::cout << s << '\n';
}
If I change "std::string::n pos" to "s.length() "
Note that 'size()' and 'length()' are two functions which
have exactly the same effect.
then of course the
program works correctly. Why doesn't std::string::np os work in this
context?


Because you're trying to use it for something other than
it's defined purpose. Like trying to cut a watermelon with
a feather. :-)

-Mike
Jan 27 '06 #4

"Victor Bazarov" <v.********@com Acast.net> wrote in message
news:eb******** *******@newsrea d1.mlpsca01.us. to.verio.net...
If I change "std::string::n pos" to "s.length() " then of course the
program works correctly. Why doesn't std::string::np os work in this
context?


'npos' is a constant usually defined as (size_type)(-1). Its specific
purpose is to indicate "not found" condition when returning from 'find'
members and the "end" position when using 'substr'.

You mistakenly used it as if it is different for every 'string' object.
It's not. IIRC it's a static member.


I suspect that Marcus misunderstood after seeing npos used in
a different context, e.g. 'string::substr ()'s second parameter
specifies a default value of 'npos', meaning 'all'.

std::string s("hello");
std::string sub(s.substr(0) ); // now s == sub

-Mike
Jan 27 '06 #5
Bob Hairgrove <in*****@bigfoo t.com> wrote:
On Fri, 27 Jan 2006 21:06:31 +0000 (UTC), ri******@gehenn om.net
(Marcus Kwok) wrote:
std::string:: npos is described in _TC++PL:SE_ (Section 20.3.4) as the
"all characters" marker. I tried to use it this way, but my program
crashes:

#include <iostream>
#include <string>

int main()
{
std::string s = "hi/hello/now";
std::cout << s << '\n';

for (std::string::s ize_type i = 0; i != std::string::np os; ++i) {
if (s[i] == '/') {
s[i] = '\\';
}
}

std::cout << s << '\n';
}
If I change "std::string::n pos" to "s.length() " then of course the
program works correctly. Why doesn't std::string::np os work in this
context?


std::string::np os is usually just an alias for ((unsigned)(-1)). You
are therefore incrementing i way past the end of the string's length.

std::string::np os is returned by most string functions which involve
some kind of find, and which would normally return the index or
position of the element being sought. Since there can never be such a
position, this value was chosen to indicate "not found" or not
present.


Thanks. I was thinking maybe it would be similar to the .end()
iterator (as in, 1 greater than the last element).

--
Marcus Kwok
Jan 27 '06 #6
On Fri, 27 Jan 2006 21:06:31 +0000 (UTC) in comp.lang.c++,
ri******@gehenn om.net (Marcus Kwok) wrote,
std::string::n pos is described in _TC++PL:SE_ (Section 20.3.4) as the
"all characters" marker.


That statement refers specifically to the use of npos as an argument
to the string constructor that creates a substring of an existing
string. Your code is not doing anything even slightly resembling
that. Give me a break.

Jan 27 '06 #7
> Thanks. I was thinking maybe it would be similar to the .end()
iterator (as in, 1 greater than the last element).


You could always just use an iterator.
Jan 27 '06 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
8182
by: Angus Leeming | last post by:
Hello, Could someone explain to me why the Standard conveners chose to typedef std::string rather than derive it from std::basic_string<char, ...>? The result of course is that it is effectively impossible to forward declare std::string. (Yes I am aware that some libraries have a string_fwd.h header, but this is not portable.) That said, is there any real reason why I can't derive an otherwise empty
11
3662
by: Christopher Benson-Manica | last post by:
Let's say I have a std::string, and I want to replace all the ',' characters with " or ", i.e. "A,B,C" -> "A or B or C". Is the following the best way to do it? int idx; while( (idx=str.find_first_of(',')) >= 0 ) { str.replace( idx, 1, "" ); str.insert( idx, " or " ); }
1
2005
by: Chris Mantoulidis | last post by:
PROBLEM: I'm having some weird problems with string::find() (in ParamGenerate()), but since I'm not sure if that is the source of all bad output in my program, I'm posting least code that's compilable. OTHER INFO: Just so you know what the program does (and so you can give it some input to test it), at this stage I want it to break the input into some parts. Here is the input style: <middle param> <middle param> ...... <middle param>...
4
4038
by: Christopher | last post by:
I am using std::string to parse a command given by the user, I don't understand why the following snippet is not working as expected. string buffer, // store commands from user command, argument; string::size_type index = string::npos; cout<<"\nThe Following are valid commands:\n"; cout<<"read_all <number> -- display entire mail header and body.\n";
18
2429
by: JKop | last post by:
Can some-one please point me to a nice site that gives an exhaustive list of all the memberfunctions, membervariables, operators, etc. of the std::string class, along with an informative description of how each works. I've been trying Google for the last 20 minutes but can't get anything decent. Thanks.
2
5512
by: FBergemann | last post by:
if i compile following sample: #include <iostream> #include <string> int main(int argc, char **argv) { std::string test = "hallo9811111z"; std::string::size_type ret;
8
2540
by: Marcus Kwok | last post by:
Is std::string::npos portably able to be incremented? For example, I want to insert some text into a string. If a certain character is found, I want to insert this text immediately after this character; otherwise I insert at the beginning of the string. On my implementation string::npos has the value of (string::size_type)-1, so incrementing it will make it 0, but can I rely on it? Also, say that the character occurs at the end of...
11
4282
by: Christopher Pisz | last post by:
Is std::string::npos always going to be less than any std::string 's size()? I am trying to handle a replacement of all occurances of a substr, in which the replacement also contains the substr. Yick. All I could come up with is: #include <string> int main() { std::string text;
7
4268
by: Hendrik Schober | last post by:
Hi, this #include <string> class test { typedef std::string::size_type size_type; static const size_type x = std::string::npos; }; doesn't compile using either VC9 ("expected constant expression") or Comeau Online ("constant value is not known"). If I replace
0
9425
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10053
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10001
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9867
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8880
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7415
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6676
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5312
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
3
2816
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.