473,785 Members | 2,746 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

std::string::np os always < std::string::si ze() ?

Is std::string::np os 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;
text = "\nThis is a test line with newlines\n<-here and \n<-here and
\n\n<-two here";

// Format the text
std::string formattedText(t ext);

// Change every occurrance of "\n" to "\r\n"
std::string::si ze_type index = 0;

do
{
index = formattedText.f ind('\n', index);
if( index != std::string::np os )
{
formattedText.i nsert(index, "\r");
index += 2;
}
} while( index < formattedText.s ize() );

// debugging contents of formattedText here

return 0;
}

However, it depends on std::string::np os always being less than the size of
the string and I am not certain whether that is safe or not.
Jan 10 '08
11 4289
In article <OQ************ @newsfe06.lga>, ta*******@rocke tmail.com
says...

[ ... ]
I do ( var = something ) == something
all the time, and have always considered it clean.
I don't see much reason to do it in the case of the code earlier in this
thread, but in some cases, I think this is exactly the correct thing to
do.

Just for one example, I believe when writing code to open a file using
fopen, the correct way to do it is something like:

if (NULL==(file=fo pen(whatever, "r")))
// handle error

Getting into the habit of coding this way assures that a problem with
opening the file will always be handled. Code that separates opening and
testing:

file = fopen(whatever, "r");

if ( file == NULL)
// handle error

....makes some types of errors much easier. One is leaving out the
testing code entirely. The other is accidentally inserting something
between opening and testing that depends on the file having been opened
correctly. Both are obviously errors, but are also easy to miss until
the code is tested with a file that can't be opened.

--
Later,
Jerry.

The universe is a figment of its own imagination.
Jan 12 '08 #11
On Jan 12, 4:46 am, Jerry Coffin <jcof...@taeus. comwrote:
In article <OQwhj.42$QA... @newsfe06.lga>, tazmas...@rocke tmail.com
says...
[ ... ]
I do ( var = something ) == something
all the time, and have always considered it clean.
I don't see much reason to do it in the case of the code
earlier in this thread, but in some cases, I think this is
exactly the correct thing to do.
Just for one example, I believe when writing code to open a
file using fopen, the correct way to do it is something like:
if (NULL==(file=fo pen(whatever, "r")))
// handle error
Getting into the habit of coding this way assures that a
problem with opening the file will always be handled. Code
that separates opening and testing:
file = fopen(whatever, "r");
if ( file == NULL)
// handle error
...makes some types of errors much easier. One is leaving out
the testing code entirely. The other is accidentally inserting
something between opening and testing that depends on the file
having been opened correctly. Both are obviously errors, but
are also easy to miss until the code is tested with a file
that can't be opened.
I've not found this to be a problem, and do generally do the
open separately. Especially with [io]fstream:
std::ifstream input( filename.c_str( ) ) ;
if ( ! input.is_open() ) ...
If there is an exception to my rule, however, it is when the
return value contains an error indicator---especially, if it is
only an error indicator---and the function has serious side
effects otherwise. Personally, I don't nest the assignment if
the return value is saved, but I don't have too much problem
with people who write things like:
while ( (length = read( fd, buffer, bufSize )) 0 ) {
}
, and of course, I do write things like:
while ( std::getline( input, line ) ) {
}
which is really fairly similar, except that the additional state
is saved in the iostream object (i.e. failbit, eofbit, etc.),
and not in a variable that I explicitly assign. Ideally, one
would like for a condition never to have any side effects, but
sometimes, the cure is worse than the disease (although the only
problem I have with something like:

std::getline( input, line ) ;
while ( input ) {
//...
std::getline( input, line ) ;
}

is that it isn't idiomatic. Independantly of any other
advantages or disadvantages, an experienced C++ programmer who
sees it will ask himself why the idiomatic form wasn't used.

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jan 13 '08 #12

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

Similar topics

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 " ); }
25
2994
by: Jason | last post by:
Hi, below is example code which demonstrates a problem I have encountered. When passing a number to a function I compare it with a string's size and then take certain actions, unfortunately during the testing of it I discovered that negative numbers were being treated as if they were > 0. I compiled the following on mingw compiler/dev c++/windows xp. If I replace string.size() for a ordinary number it behaves as expected? I notice...
1
4410
by: Tero Toivanen | last post by:
Dear experts, I am doing code to Solaris 9 system with C++. I get every now and then segmentation fault in the following code that removes heading and trailing white spaces (mLineStr is of type std:string): ------
15
6905
by: roberts.noah | last post by:
Are there any decent benchmarks of the difference between using c strings and std::string out there? Google isn't being friendly about it. Obviously this would be dependant on different implementations but I don't care. I would be happy to find ANY comparison at this point if it was valid and semi scientifically done.
7
4871
by: Marcus Kwok | last post by:
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";
2
5514
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;
10
9070
by: lovecreatesbea... | last post by:
Is it correct and safe to compare a string object with "", a pair of quotation marks quoted empty string?If the string object: s = ""; does s contain a single '\'? Is it better to use std::string::size or std::string::empty to deal with this condition? Thank you. string s = ""; if (s == ""); if (s.size == 0); if (s.empty());
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...
8
13765
by: Edson Manoel | last post by:
I have some C++ unmanaged code that takes std::string& arguments (as reference), and fills them (possibly growing the string). I want to call this code through PInvoke (DllImport), possibly using wrapper layers in unmanaged C++ and C#. I've thought about two approaches: 1) To pass a StringBuilder, this is converted to a char* in C++, the wrapper code converts the char* to a std::string (copy), and in the
0
9643
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10319
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10147
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
10087
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
9947
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
8971
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
7496
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
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3645
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.