473,769 Members | 8,267 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Help with std::string to char[128]

Ive searched and searched,but havent been able to get it to work.
-----------------
#include <iostream>

using namespace std;

std::string tempHostNameStr = "s1e2.hidden.th ingy.org";
char szHostName[128];

for(int i=0; i < std::string tempHostNameStr .size(); i++){
szHostName[i] = tempHostNameStr[i];}
Errors:
C:\Documents and Settings\Daniel \Mina dokument\c++\st ringtest.cpp:13 :
error: expected unqualified-id before "for"
C:\Documents and Settings\Daniel \Mina dokument\c++\st ringtest.cpp:13 :
error: expected `,' or `;' before "for"
C:\Documents and Settings\Daniel \Mina dokument\c++\st ringtest.cpp:13 :
error: expected constructor, destructor, or type conversion before '<'
token
C:\Documents and Settings\Daniel \Mina dokument\c++\st ringtest.cpp:13 :
error: expected `,' or `;' before '<' token
C:\Documents and Settings\Daniel \Mina dokument\c++\st ringtest.cpp:13 :
error: expected constructor, destructor, or type conversion before '++'
token
C:\Documents and Settings\Daniel \Mina dokument\c++\st ringtest.cpp:13 :
error: expected `,' or `;' before '++' token

Execution terminated

-----------------
Ive also tried using .c_str(),and assigning it directly by szHostName =
tempHostNameStr ;

Anyone got a suggestion?

Sep 9 '06 #1
6 4860
St*******@gmail .com schrieb:
Ive searched and searched,but havent been able to get it to work.

[snipped: incomplete program]

Errors:
C:\Documents and Settings\Daniel \Mina dokument\c++\st ringtest.cpp:13 :
error: expected unqualified-id before "for"

[snipped: error messages, all about the same origin]
Execution terminated

-----------------
Ive also tried using .c_str(),and assigning it directly by szHostName =
tempHostNameStr ;
This is course couldn't work. Either use strncpy(), or the for-loop you
tried (but see comments below).
Anyone got a suggestion?
Did you
#include <string>
?

It would have been nice to see the minimal, ought-to-work program. This
is it not, as there is no main() etc. etc. I just can guess if you just
forgot to post your #include directive or not.

Additionally, about such for-loops:

* use size_t for i, if you compare against a size_t. Then the compiler
will also not complain about comparison of signed with unsigned
values.
* check if your destination buffer is big enough for your string! And
no, "but this string will only have max. 60 chars!" is no argument.
Even for trivial programs, as you will import such a lazy style into
your more serious work (or into your exam, where it will have a bad
impact on your grade).

Finally: Why do you want to do this? As an inexperienced programmer you
could not care less about traditional C-style arrays and strings, as the
C++ classes are there for a reason: they make life easier, and more
safe. If you write about your problem, we maybe can point out a better
solution in the first place.
best regards,
-- Markus

Sep 9 '06 #2
St*******@gmail .com wrote:
>
for(int i=0; i < std::string tempHostNameStr .size(); i++){
Get rid of the std::string. You'll also have to stick a terminating null
character after the characters that you copy.

--

-- Pete

Author of "The Standard C++ Library Extensions: a Tutorial and Reference."
For more information about this book, see www.petebecker.com/tr1book.
Sep 9 '06 #3

<St*******@gmai l.comwrote in message
news:11******** **************@ h48g2000cwc.goo glegroups.com.. .
Ive searched and searched,but havent been able to get it to work.
-----------------
#include <iostream>

using namespace std;

std::string tempHostNameStr = "s1e2.hidden.th ingy.org";
char szHostName[128];

for(int i=0; i < std::string tempHostNameStr .size(); i++){
szHostName[i] = tempHostNameStr[i];}
for ( int i = 0; i < tempHostNameStr .size(); ++i )

get rid of the std::string here. But you might as well use strcpy.

std::string tempHostNameStr = "s1e2.hidden.th ingy.org";
char szHostName[128];
if ( tempHostNameStr .size() 127 )
{
std::cout << "Evil! Host name too long!" << std::endl;
return 0;
}
else
strcpy( szHostName, tempHostNameStr .c_str() );

It looks like you are doing this copy, however, because you are using a call
that wants a char* and you have a std::string. std::string has the c_str()
that returns a pointer to a c-style string (null terminated char array). It
is const, however, meaning you can't change it.

SomeNetworkFunc tion( tempHostNameStr .c_str() );

A lot of times some calls won't be const correct. That is, they will ask
for a char* although they don't change the contents and really should be
const char*. In these cases it is *usually* safe to do a const_cast to
throw away the constantness of the c_str() but you have to be 1000% sure
that the function won't try to change the string.

SomeNetworkFunc tion( cost_cast<char* >( tempHostNameStr .c_str() );

HTH

Also, of course, remember to
#include <string>
Sep 10 '06 #4
Thanks for all your answers I appriciate your fast respond time:) i
decided to go for the forloop with a \0 at the end.
I dont know what was wrong,but why do you want me to include string?
dosn't iostream contain it? Im very sorry but im just a starter at c++

Sep 11 '06 #5

St*******@gmail .com wrote:
Thanks for all your answers I appriciate your fast respond time:) i
decided to go for the forloop with a \0 at the end.
I dont know what was wrong,but why do you want me to include string?
dosn't iostream contain it? Im very sorry but im just a starter at c++
Standard headers are permitted to include other standard headers, but
there are no requirements that any particular standard header includes
any other particular standard header.

If you rely on the fact that in your particular standard library
implementation, header <abcincludes header <xyz>, then you might find
your code does not compile when you change to a different compiler or
standard library implementation. To avoid this problem, whenever you
use a standard library component, always explicitly include the header
that declares it. std::cout is declared in <iostream>. If you use
std::cout, #include <iostream>. std::string is declared in <string>. If
you use std::string, #include <string>. That way, your code will always
work, regardless of what the standard library implementation you are
using that day does in terms of standard headers including other
standard headers.

As a side issue, I'd be somewhat surprised if <iostreaminclud ed
<string>, though it is not forbidden. But anyway, as I said above, even
if it does that in your implementation, you should not rely on it.

Gavin Deane

Sep 11 '06 #6
St*******@gmail .com wrote:
Thanks for all your answers I appriciate your fast respond time:) i
decided to go for the forloop with a \0 at the end.
I dont know what was wrong,but why do you want me to include string?
dosn't iostream contain it? Im very sorry but im just a starter at c++
Each standard header is required to define certain names. Any reasonable
reference guide will tell you which names must be defined by each of the
standard headers. Standard headers are also allowed, but not required
to, define other names, since some other names are often needed in order
for the definitions of the required names to make sense. But having
found that some standard header defines a name that it's not required to
define, you cannot conclude that it also defines all the other names
defined in the header that's required to define that name. So, for
example, if <iostreamhappen s to provide the definition of
std::basic_stri ng, you can't assume that it also provides the name
std::string.

In general, when you use any name from the standard library, include the
header that's required to define it.

--

-- Pete

Author of "The Standard C++ Library Extensions: a Tutorial and Reference."
For more information about this book, see www.petebecker.com/tr1book.
Sep 11 '06 #7

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

Similar topics

20
2687
by: titi | last post by:
Question The road and traffic authority for a small country currently uses a system to store information about all 'currently' licensed drivers. A licensed driver has the following info stored about them in a record; 1. Given name(s) of the license holder.(not more than 128 char (may have spaces)). 2. Surname of the license holder.(Not more then 128 same like above).
1
3411
by: James Vanns | last post by:
I want to be able to print out (and read in) characters with accents (for example French and Italian text). So far I have this: std::locale lang (getenv ("LANG")); which seems to set the locale correctly, say to it_IT.utf8 (on UNIX). However, when reading in text from a file using:
37
7362
by: Zombie | last post by:
Hi, what is the correct way of converting contents of a <string> to lowercase? There are no methods of <string> class to do this so I fallback on strlwr(). But the c_str() method returns a const pointer which cannot be used with strlwr() as it does the conversion inplace. So, I use the following logic of copying the contents to a dynamically allocated char* array and then doing the conversion: -----------------------------
3
1507
by: sudeep | last post by:
C++ Programming Language Assignment 1 Associative Array Class Problem Statement Associative arrays are a useful feature found in many languages particularly in those that are interpretive and support dynamic variables, such as awk, perl, APL, etc. An associative array is very much like the much familiar array, with the only difference that the index specified, can be of any type. (In arrays, array index HAS TO BE integer). An...
6
6645
by: Khuong Dinh Pham | last post by:
How do i read the contents of a xml file and output it to a std::string. Thx in advance
0
2562
by: sanjana | last post by:
hi i want to write a C# .net code to display a balloon in the task bar i have used notifyicon class to get the icon in the task bar then i have used Shell_NotifyIcon and NotifyIconData structure for getting the balloon So now i have an icon n a balloon in the task bar But i wan tht when i click on the yellow windows balloon an event should be fired I know tht i have to use NIN_BALLOONUSERCLICK of Shell_NotifyIcon for
43
8457
by: Steven T. Hatton | last post by:
http://public.research.att.com/~bs/bs_faq2.html#int-to-string Is there no C library function that will take an int and convert it to its ascii representation? The example Bjarne shows in his faq is not extremely convenient. -- NOUN:1. Money or property bequeathed to another by will. 2. Something handed down from an ancestor or a predecessor or from the past: a legacy of religious freedom. ETYMOLOGY: MidE legacie, office of a deputy,...
3
2122
by: bob | last post by:
Hi, I'm looking at a legacy string class thats been in use here for a while and I'd like to check out any options available to optimise it. I see a couple of constructors that look dubious. Consider the following ctor. It constructs a TtkString object with a string value of the integer contained withing. e.g TtkString one(456); cout << one << endl;
3
18109
by: schizoid_man | last post by:
Hi, I have the following code snippets and I get a std::bad_alloc error where I think there should be none. I've attached the relevant bits of the base class, derived class and the .cpp file containing the main() method. I'd really appreciate any help in getting this error sorted out. Thanks,
0
9589
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
9423
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
10216
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
10049
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
9997
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
8873
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
7413
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
5310
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...
0
5448
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.