473,659 Members | 2,662 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

what difference between c_str() and begin()

string s = "hello";
const char *p = s.begin();
cout << p << endl; // print hello

s = "";

char *p2= s.begin();

cout << p2 << endl; // print hello why?????
I don't know why p2 is not "" ?

if p2 change iterator as fellow
string::iterato r p2 = s.begin();

the result is the same
what difference between begin() and c_str()

or my problem should focus on operator<< ?

--
Origin: ¤¤¥¿¤j¾Ç£»GAIS¤ý´Â  gais.twbbs.org 
Author: diadia ±q gais5.cs.c cu.edu.tw µoªí
Jul 23 '05 #1
2 3658
diadia wrote:
string s = "hello";
const char *p = s.begin();
This is not necessarily well-formed. No requirement is placed on the
'std::string::i terator' that it should be convertible to a pointer to
const char. Your program depends on implementation-defined behaviour
and as such is non-portable.
cout << p << endl; // print hello
On your system it might print hello, on my system it may not compile.
s = "";

char *p2= s.begin();

cout << p2 << endl; // print hello why?????
Because the data apparently didn't change. The string simply sets
its size to 0 to indicate that it has no chars stored, most probably.

Whatever you get as the result of outputting the value you obtain by
calling 'begin()' is inconsequential because it's implementation-defined.
I don't know why p2 is not "" ?
Why should it be? What is definite is that p2 == s.end(), and that
should mean that the string is empty. That's the only thing that is
required WRT iterator values, after you clear the string.
if p2 change iterator as fellow
string::iterato r p2 = s.begin();

the result is the same
What do you mean "the same"?
what difference between begin() and c_str()
One of them returns an iterator, the other returns a pointer to const
char that points to some place that contains the characters the same as
in the string.
or my problem should focus on operator<< ?


Your problem should focus on the correct use of iterators.

V
Jul 23 '05 #2

"diadia" <di********@gai s.twbbs.org> wrote in message
news:4H******** @gais.twbbs.org ...
string s = "hello";
const char *p = s.begin();
cout << p << endl; // print hello

s = "";

char *p2= s.begin();

cout << p2 << endl; // print hello why?????
I don't know why p2 is not "" ?
It can't be. p2 isn't pointing to a std::string. p2 is pointing to an array
of characters wich expects a \0 terminator to denote the end of the old_type
cstring. In fact, s.c_str() does exactly that, returns a const pointer to a
char array which includes the terminator.

#include <iostream>
#include <iterator>
#include <string>

int main(int argc, char* argv[])
{
std::string s("string");

const char *p = s.c_str(); // not a mismatch
std::cout << p << std::endl;

s = "";

const char *p2 = s.c_str();
std::cout << p2 << std::endl;

s = "modified string";

std::string::it erator iter;
for (iter = s.begin(); iter != s.end(); ++iter)
{
std::cout << *iter; // iterate through each char
}

return 0;
}

A std::string doesn't need a terminator since it maintains a variable to
track its own length (think: container). Initializing a std::string and
ignoring that fact results in undefined behaviour.

if p2 change iterator as fellow
string::iterato r p2 = s.begin();

the result is the same
as expected


what difference between begin() and c_str()
Night and day, the first returns a std::string iterator and the second a
constant pointer to a terminated char array.

or my problem should focus on operator<< ?
Has nothing to do with the stream operator.

--
Origin: ¤¤¥¿¤j¾Ç£»GAIS¤ý´Â  gais.twbbs.org  Author: diadia ±q gais5.cs.c cu.edu.tw

µoªí
Jul 23 '05 #3

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

Similar topics

2
2693
by: klaus hoffmann | last post by:
In the following program I would expect r to be a zero terminated string of length 1. Am I wrong? The STL I'm using omit the zeroterm in this situation. Klaus #include <iostream> using namespace std; //introduces namespace std int main(){ string x("12");
2
9187
by: Tony Murphy | last post by:
I've got an application that sends emails (not spam!). The application reads a template file (html/text) into a string, the string is processed and placeholders filled in as appropiate. I call a 3rd party api for sending the email, the api is written in c, so i need to convert the string into LPSTR (windows c style string?), i'm from unix world and new to windows mutant. I know that c_str() converts a string to a c string and data()...
15
11595
by: Derek | last post by:
I'm curious about the performance of string::c_str, so I'm wondering how it's commonly implemented. Do most std::string implementations just keep an extra char allocated for the NULL termination so they can return a pointer to their internal buffer, or are they equally likely to create a new buffer on demand? I know the standard doesn't require any particular implementation, which is why I'm curious if there is a consensus among...
2
3081
by: Vyacheslav Kononenko | last post by:
All, If I am not mistaken I had some problems with code like this: std::string foo, bar; .... somefunc( foo.c_str(), bar.c_str() ); Problem was that c_str() used buffer shared btw instances of std::string in that implementation. I did not find anything that
18
7819
by: Metro12 | last post by:
In the <basic_string.h>, I find the implementation of these two functions. But I can't understand the difference between them. Please give me some help! //basic_string::c_str() const _CharT* c_str() const { // MT: This assumes concurrent writes are OK. size_type __n = this->size(); traits_type::assign(_M_data(), _Rep::_S_terminal);
2
6447
by: ma740988 | last post by:
Consider: bool transmit ( const char* pch, size_t len ) { int const val = strcmp( pch, "who_am_i" ); if ( val == 0 ) return ( true ); return ( false ); }
12
5263
by: shyam | last post by:
Hi I have a program within which i have the following statement. sprintf(somevar,"%s/%s.%s",PREFIX.c_str( ),MIDDLE.c_str( ),SUFFIX.c_str( ) ); Here PREFIX, MIDDLE and SUFFIX are all const strings. This works fine but recently after close to 1000 successful runs my
6
4206
by: bleyddyn.apRhys | last post by:
I have a bit of code that doesn't compile under MSVC++ but does under GCC. Even under GCC, though, it seems odd that I don't need a std namespace qualifier for the exp function. Is this just one of those difference I have to #ifdef around, or is there a bit of code that will compile under both? Basically, I have a std::vector<double>. I want to replace each item in the vector with the exp() of that item. The code does work, and...
123
6413
by: plenty900 | last post by:
I was looking over someone's C++ code today and despite having written perfectly readable C++ code myself, the stuff I was looking at was worse than legalese. The people who are guiding the development of C++ have really made a mess of things, I mean templates and competing libraries and all that just render the code impossible to comprehend. Sure there is going to be a certain amount of complexity, that's a given, but if code is not...
0
8330
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
8850
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...
1
8523
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
8626
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
7355
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
6178
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
5649
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
4175
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...
1
2749
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.