• Log InLog In
  • Register
Liquid`
Team Liquid Liquipedia
EST 08:54
CET 14:54
KST 22:54
  • Home
  • Forum
  • Calendar
  • Streams
  • Liquipedia
  • Features
  • Store
  • EPT
  • TL+
  • StarCraft 2
  • Brood War
  • Smash
  • Heroes
  • Counter-Strike
  • Overwatch
  • Liquibet
  • Fantasy StarCraft
  • TLPD
  • StarCraft 2
  • Brood War
  • Blogs
Forum Sidebar
Events/Features
News
Featured News
RSL Season 3 - RO16 Groups C & D Preview0RSL Season 3 - RO16 Groups A & B Preview2TL.net Map Contest #21: Winners12Intel X Team Liquid Seoul event: Showmatches and Meet the Pros10[ASL20] Finals Preview: Arrival13
Community News
[TLMC] Fall/Winter 2025 Ladder Map Rotation13Weekly Cups (Nov 3-9): Clem Conquers in Canada4SC: Evo Complete - Ranked Ladder OPEN ALPHA8StarCraft, SC2, HotS, WC3, Returning to Blizzcon!45$5,000+ WardiTV 2025 Championship7
StarCraft 2
General
Zerg is losing its identity in StarCraft 2 [TLMC] Fall/Winter 2025 Ladder Map Rotation Mech is the composition that needs teleportation t RotterdaM "Serral is the GOAT, and it's not close" RSL Season 3 - RO16 Groups C & D Preview
Tourneys
RSL Revival: Season 3 Sparkling Tuna Cup - Weekly Open Tournament Constellation Cup - Main Event - Stellar Fest Tenacious Turtle Tussle Master Swan Open (Global Bronze-Master 2)
Strategy
Custom Maps
Map Editor closed ?
External Content
Mutation # 499 Chilling Adaptation Mutation # 498 Wheel of Misfortune|Cradle of Death Mutation # 497 Battle Haredened Mutation # 496 Endless Infection
Brood War
General
FlaSh on: Biggest Problem With SnOw's Playstyle BGH Auto Balance -> http://bghmmr.eu/ What happened to TvZ on Retro? SnOw's ASL S20 Finals Review BW General Discussion
Tourneys
[Megathread] Daily Proleagues Small VOD Thread 2.0 [BSL21] RO32 Group D - Sunday 21:00 CET [BSL21] RO32 Group C - Saturday 21:00 CET
Strategy
PvZ map balance Current Meta Simple Questions, Simple Answers How to stay on top of macro?
Other Games
General Games
Clair Obscur - Expedition 33 Should offensive tower rushing be viable in RTS games? Path of Exile Stormgate/Frost Giant Megathread Nintendo Switch Thread
Dota 2
Official 'what is Dota anymore' discussion
League of Legends
Heroes of the Storm
Simple Questions, Simple Answers Heroes of the Storm 2.0
Hearthstone
Deck construction bug Heroes of StarCraft mini-set
TL Mafia
TL Mafia Community Thread SPIRED by.ASL Mafia {211640}
Community
General
Things Aren’t Peaceful in Palestine US Politics Mega-thread Russo-Ukrainian War Thread Artificial Intelligence Thread Canadian Politics Mega-thread
Fan Clubs
White-Ra Fan Club The herO Fan Club!
Media & Entertainment
Movie Discussion! [Manga] One Piece Anime Discussion Thread Korean Music Discussion Series you have seen recently...
Sports
2024 - 2026 Football Thread Formula 1 Discussion NBA General Discussion MLB/Baseball 2023 TeamLiquid Health and Fitness Initiative For 2023
World Cup 2022
Tech Support
SC2 Client Relocalization [Change SC2 Language] Linksys AE2500 USB WIFI keeps disconnecting Computer Build, Upgrade & Buying Resource Thread
TL Community
The Automated Ban List
Blogs
Dyadica Gospel – a Pulp No…
Hildegard
Coffee x Performance in Espo…
TrAiDoS
Saturation point
Uldridge
DnB/metal remix FFO Mick Go…
ImbaTosS
Reality "theory" prov…
perfectspheres
Customize Sidebar...

Website Feedback

Closed Threads



Active: 2241 users

[C++] Using std::string as a Function Parameter?

Blogs > Revabug
Post a Reply
Normal
Revabug
Profile Blog Joined June 2009
United Kingdom147 Posts
Last Edited: 2009-07-20 22:41:01
July 20 2009 22:33 GMT
#1
Okay so I've just started to learn C++..

After messing around with std::stings for a while I came up with the abstract idea of creating a function that returned the length of the string (not including whitespace)

Here's what I came up with:
+ Show Spoiler +

int Characters(string strString)
{
int nLength = 0;
for (int nChar = 0; nChar < strString.Length(); nChar++)
{
if (strString[nChar] != ' ')
nLength++;
}
return nLength;
}


However, of course this doesn't compile as std::string isn't a valid function parameter. So I ask, how could I get this to work? I've googled and check various tutorial sites but I haven't found anything on this.



Archaic
Profile Blog Joined March 2008
United States4024 Posts
July 20 2009 22:38 GMT
#2
I'm not a C++ programmer, but do you have to close the parentheses in the if statement? Also, should the for statement be nChar < strString.Length()? I don't know what >> means, but I'm just guessing it is greater than.
Revabug
Profile Blog Joined June 2009
United Kingdom147 Posts
Last Edited: 2009-07-20 22:41:31
July 20 2009 22:40 GMT
#3
Yeah I had to type it out cause it wouldn't copy for some reason so there's some random mistakes but the actual code is fine (well, apart from it doesn't work :X)
micronesia
Profile Blog Joined July 2006
United States24741 Posts
July 20 2009 22:42 GMT
#4
Wait, couldn't you just return strString.length()? What exactly is going on lol.

When I did c++ I always used the AP Include files so I have no idea how to do string without apstring.h XD
ModeratorThere are animal crackers for people and there are people crackers for animals.
Archaic
Profile Blog Joined March 2008
United States4024 Posts
Last Edited: 2009-07-20 22:45:12
July 20 2009 22:44 GMT
#5
micronesia brings up a good point... This function is completely useless. You could just use string.Length() instead of creating a method to do the exact same thing.
EDIT: Just a random question, when using greater/less than signs, is it still shifters in C++ like in Java?
Revabug
Profile Blog Joined June 2009
United Kingdom147 Posts
Last Edited: 2009-07-20 22:45:49
July 20 2009 22:44 GMT
#6
?

I don't want to include whitespaces (as I said in the op), so strString.Length() won't work
GogoKodo
Profile Blog Joined April 2003
Canada1785 Posts
July 20 2009 22:47 GMT
#7
On July 21 2009 07:42 micronesia wrote:
Wait, couldn't you just return strString.length()? What exactly is going on lol.

When I did c++ I always used the AP Include files so I have no idea how to do string without apstring.h XD

He's trying to get the length minus the whitespace I guess.
twitter: @terrancem
VarmVaffel
Profile Blog Joined June 2008
Norway378 Posts
Last Edited: 2009-07-20 22:49:46
July 20 2009 22:48 GMT
#8
In any case, since you say that string isn't a valid parameter, my guess is that you have forgotten to include string.h, or to use the std namespace.
GogoKodo
Profile Blog Joined April 2003
Canada1785 Posts
July 20 2009 22:49 GMT
#9
Not sure about your function since it's been so long since I did c++ but you should be able to google for c++ string function arguments to find the correct way.

On another note, currently you are only getting rid of the ' ' (spaces) in your count, and not any whitespace such as a tab. Might want to look into that as well.
twitter: @terrancem
Revabug
Profile Blog Joined June 2009
United Kingdom147 Posts
July 20 2009 22:49 GMT
#10
(not including whitespace)

I don't want to include whitespaces

He's trying to get the length minus the whitespace I guess.


Adeny
Profile Blog Joined January 2009
Norway1233 Posts
Last Edited: 2009-07-20 22:55:25
July 20 2009 22:50 GMT
#11
Still, the actual length of the string and the string doesn't change, so the returned value from strString.length() will be constant throughout the entire loop no matter how many whitespaces. Just return strString.length() to a nSomething and use nChar < nSomething in the loop. I can't see why this wouldn't work?

To clarify, say your string is "HI MOM".

You get the length of the string which is 6 characters.
You loop through, count the H, nLength ++1;
Loop through, count the I, nLength ++1;
Loop through, won't count the whitespace.
Loop through, counts the M, nLength ++1;
Loop through, counts the O, nLength ++1;
Loop through, counts the M, nLength ++1;

At the end of this, you will have the length of the actual string which will still be 6 characters, and the nLength variable which you individually use to count the characters except for the whitespace which will be 5.
b3h47pte
Profile Blog Joined May 2007
United States1317 Posts
July 20 2009 22:50 GMT
#12
What IDE are you using? I loaded your code up into Visual Studios 2008 and it works fine.
http://pastebin.com/m1fe7c353

Results in

[image loading]


are you making sure you include iostream and using namespace std?
GogoKodo
Profile Blog Joined April 2003
Canada1785 Posts
July 20 2009 22:51 GMT
#13
Ok after a quick google I found some code using this syntax

void function (std::string &str)
{
}
twitter: @terrancem
Archaic
Profile Blog Joined March 2008
United States4024 Posts
July 20 2009 22:52 GMT
#14
Oh, I see what you mean now! If you want to ignore tabs, you may consider using the C++ equivalent of the Java:
strString[nChar] != ' ' && !(strString[nChar]+"").equals("\t");
The second part is converting the character to a string, to use .equals() function (in Java, Strings don't use ==), and comparing it to the string of a tab (\t).
But other than that, I can't really see an obvious problem. You may consider issues not within the code, but within your compiler.
GogoKodo
Profile Blog Joined April 2003
Canada1785 Posts
July 20 2009 22:53 GMT
#15
Make sure you're compiling the correct up to date version of the code and using the updated executable. Silly thing to point out but this is what cause several pages of confused people in konadora's blog asking for programming help.
twitter: @terrancem
Revabug
Profile Blog Joined June 2009
United Kingdom147 Posts
Last Edited: 2009-07-20 22:59:40
July 20 2009 22:59 GMT
#16
I didn't realise I needed to add using namespace std; before the function, I thought I could just add it in int main() where the function would get called because that's when it would be run first..

Thanks
b3h47pte
Profile Blog Joined May 2007
United States1317 Posts
July 20 2009 23:21 GMT
#17
I'm glad I (we) could help! Good luck learning C++! It's a rewarding experience.
2Pacalypse-
Profile Joined October 2006
Croatia9517 Posts
July 20 2009 23:49 GMT
#18
I'm a C programmer, and I'm just wondering did C++ abandon pointers completely or can you still use them?

Moderator"We're a community of geniuses because we've found how to extract 95% of the feeling of doing something amazing without actually doing anything." - Chill
b3h47pte
Profile Blog Joined May 2007
United States1317 Posts
July 20 2009 23:54 GMT
#19
yea you can use pointers in C++.
2Pacalypse-
Profile Joined October 2006
Croatia9517 Posts
July 21 2009 00:08 GMT
#20
Oh ok.
And sorry for taking over the thread, but what's with this string data type?
What's the difference between string type and char[]?

Even though I prefer C over all other programs, I'm gonna have to do some C++ for uni this year so just getting prepared I guess...
Moderator"We're a community of geniuses because we've found how to extract 95% of the feeling of doing something amazing without actually doing anything." - Chill
b3h47pte
Profile Blog Joined May 2007
United States1317 Posts
July 21 2009 00:17 GMT
#21
char[] is the C way and string is the C++ way
a string is pretty much a character array.
Cambium
Profile Blog Joined June 2004
United States16368 Posts
July 21 2009 00:34 GMT
#22
use (const char* string) in your parameter?
When you want something, all the universe conspires in helping you to achieve it.
TanGeng
Profile Blog Joined January 2009
Sanya12364 Posts
Last Edited: 2009-07-21 00:48:56
July 21 2009 00:43 GMT
#23
You should definitely pass by reference.

int Characters(const std::string &strString); is much preferred.

Here you aren't going to run a copy constructor on the string on every call. The const also tells the compiler that you aren't going to change any of the contents of the obj during the call.

nvm the edit.
Moderator我们是个踏实的赞助商模式俱乐部
Queequeg
Profile Joined September 2003
Germany263 Posts
July 21 2009 01:48 GMT
#24
http://lmgtfy.com/?q=std string
http://www.cplusplus.com/reference/string/string/
std::string is a class, char[] isn't.
coltrane
Profile Blog Joined June 2008
Chile988 Posts
July 21 2009 02:17 GMT
#25
look, the thing is simple, the namespaces are wrong.


You can do either:

#
#
using namespace std;

after every include to set std for every variable
Or

std::string

any time you define a string variable.

This is because the namespace can be different, you could use other Library sets or the same with other names on the Classes.


In the default set of librarys you should put like header of your main

#include<string.h>
using namespace std;


And then your function will compile with no problem.
Jävla skit
coltrane
Profile Blog Joined June 2008
Chile988 Posts
July 21 2009 02:20 GMT
#26
On July 21 2009 08:49 2Pacalypse- wrote:
I'm a C programmer, and I'm just wondering did C++ abandon pointers completely or can you still use them?




Nono, advanced c++ is all about pointers... is much better for making some vector type or list type classes.
Jävla skit
Exteray
Profile Blog Joined June 2007
United States1094 Posts
July 21 2009 03:02 GMT
#27
On July 21 2009 07:51 GogoKodo wrote:
Ok after a quick google I found some code using this syntax

void function (std::string &str)
{
}



This one includes a "&" which passes the argument by reference. It changes the value of the parameter. Although the program won't change the string, it is unnecessary here.
TanGeng
Profile Blog Joined January 2009
Sanya12364 Posts
July 21 2009 03:17 GMT
#28
Unnecessary, but still good style. Passing by value implicitly triggers the copy constructor on call and a destructor on exit. Passing by reference does neither.

If the function is used with any frequency, you'll copy strings and destroy strings over and over again. It'll be slow. Classes are not to be passed by value unless absolutely necessary. Start practicing good programming style on the simple examples and it'll come naturally later.
Moderator我们是个踏实的赞助商模式俱乐部
NicolBolas
Profile Blog Joined March 2009
United States1388 Posts
Last Edited: 2009-07-21 04:10:39
July 21 2009 04:00 GMT
#29
On July 21 2009 11:20 coltrane wrote:
Nono, advanced c++ is all about pointers... is much better for making some vector type or list type classes.


I program "advanced" C++ and I don't use pointers. Well, not bare pointers. Manly C++ is done using Boost, and therefore boost::shared_ptr. I have an infrequently updated blog about this stuff.

On July 21 2009 09:08 2Pacalypse- wrote:
And sorry for taking over the thread, but what's with this string data type?
What's the difference between string type and char[]?


C++ stuff.

First, the full name is "std::string". The "std" part is a namespace. Names in C++ can be put into separate namespaces, so that you don't have type name collisions. Like if you have one library that defines a type called "string", it can put it in the namespace "library". Thus std::string and library::string can live and function within the same program.

Second, std::string is a C++ Class. It's sort of like a struct in C, but a lot more intelligent. On the creation of a Class, you are guaranteed that a certain function will be called. This function, the constructor, allows you to do initialization work, which ensures that you never use uninitialized objects. Similarly, when the object is destroyed, another function is called that allows you to do cleanup work. Also, Classes can have functions in them that operate on the given instance of that class.

std::string is an intelligent wrapper around a char* string. It's constructor allocates memory for it. If you start adding characters beyond the length of the allocated segment, it will expand the allocated region to enclose them all. It has its own searching and comparison functions. And because its destructor will handle the deletion of the internal char*, it can never leak memory (unless you fail to destroy the std::string, in which case you leaked memory). It is in every way superior to a naked char*.
So you know, cats are interesting. They are kind of like girls. If they come up and talk to you, it's great. But if you try to talk to them, it doesn't always go so well. - Shigeru Miyamoto
ven
Profile Blog Joined December 2008
Germany332 Posts
July 21 2009 04:08 GMT
#30
manly c++ is done without ++

-_-;;
You can reach the rainbow. I'll be there to help.
haduken
Profile Blog Joined April 2003
Australia8267 Posts
Last Edited: 2009-07-21 04:12:03
July 21 2009 04:11 GMT
#31
On July 21 2009 11:20 coltrane wrote:
Show nested quote +
On July 21 2009 08:49 2Pacalypse- wrote:
I'm a C programmer, and I'm just wondering did C++ abandon pointers completely or can you still use them?




....

Why can't you just use STL libaries for them?
Rillanon.au
NicolBolas
Profile Blog Joined March 2009
United States1388 Posts
July 21 2009 04:12 GMT
#32
On July 21 2009 13:08 ven wrote:
manly c++ is done without ++

-_-;;


I've written straight-C before; that's just self-inflicted torture. Real men don't do things the hard way; they do them the smart way.
So you know, cats are interesting. They are kind of like girls. If they come up and talk to you, it's great. But if you try to talk to them, it doesn't always go so well. - Shigeru Miyamoto
MasterOfChaos
Profile Blog Joined April 2007
Germany2896 Posts
July 21 2009 07:31 GMT
#33
use "const string&" for string parameters you don't change
LiquipediaOne eye to kill. Two eyes to live.
KillForce
Profile Joined March 2009
Sweden36 Posts
July 21 2009 11:41 GMT
#34
A char[] is a piece of memory, and it's up to you to make sure that
this is a good string, which is usually some text followed by a
zero. When using this, you will always have to keep the zeros in mind,
and allocating your own memory, and just being very focused in
general. You'll find yourself doing a lot of malloc/strncpy/strcat,
pointer arithmetic and suchlike. It's a hassle, for newcomers and
veterans alike. These manual labour strings even harder to do right
in C++ than in C, what with exceptions and all.

An std::string takes care of the memory, allocating and releasing as
needed. In addition, it is also usable as an STL container. I
realize as I refresh the thread that the memory argument has been made
a few times already. So I'll move on (just adding that I also support
passing the string as a constant refererence).

As for the OP, the string class you want is std::string, and to use it
you must include the string header (#include <string>, NOT <string.h>,
string.h might work in some cases, but it is not standard C++). It is
true that "using namespace std" solves your immediate problem, but you
might end up with bad habits. This is explained here:
http://www.parashift.com/c -faq-lite/coding-standards.html#faq-27.5

The C++ FAQ Lite is something I would heavily recommend any c++
programmer to keep in their bookmarks. It is actually quite pragmatic
and attempts to explain things instead of just blurting out truths.

As for testing for whitespace, writing your own test can be good if
you know exactly what you want. But I'm going to throw it out here
that there is a function called std::isspace accessible through the
ctype header (#include <ctype>) that tests for all the usual
whitespace characters (' ', '\t', '\f', '\v', '\r', '\n').

As for whether C++ uses pointers or not, the answer is: yes, it does.
Not using them would not be efficient. Some people who has used them
enough learn that they are a lot of manual labour, however, and starts
to find ways around the hardships. Pointers are dumb and they can
become invalid without feedback (if someone else deletes it), or you
can forget to delete it yourself (memory leaks and strange behavior).
Smart pointers is a collective name for objects that try to manage
pointers for you. boost::shared_ptr (http://www.boost.org/) (as pointed to
earlier) is a good example of such a pointer, and is due to be
included in the next c++ standard. But this is an extensive subject.

Sorry for re-iterating a lot of others' posts .
Normal
Please log in or register to reply.
Live Events Refresh
WardiTV Korean Royale
12:00
Group Stage 1 - Group A
WardiTV559
LiquipediaDiscussion
Kung Fu Cup
12:00
2025 Monthly #3: Day 5
Cure vs herOLIVE!
Reynor vs TBD
RotterdaM693
TKL 366
IndyStarCraft 269
SteadfastSC122
IntoTheiNu 43
Liquipedia
[ Submit Event ]
Live Streams
Refresh
StarCraft 2
RotterdaM 617
TKL 352
Tasteless 324
Reynor 276
IndyStarCraft 269
Rex 147
SteadfastSC 113
Railgan 25
MindelVK 21
StarCraft: Brood War
Britney 36790
Rain 8932
Sea 4139
firebathero 4096
BeSt 1748
Horang2 1687
GuemChi 939
Soma 605
EffOrt 552
Stork 500
[ Show more ]
Mini 456
actioN 283
Rush 225
Killer 174
Last 146
Hyun 144
scan(afreeca) 136
hero 133
Bonyth 99
Mind 90
Barracks 61
Sharp 51
zelot 50
yabsab 49
Sea.KH 45
sorry 42
Snow 39
sas.Sziky 24
Shinee 18
Hm[arnc] 15
NaDa 8
Bale 6
Dota 2
singsing3070
qojqva1678
Dendi1083
Gorgc737
XcaliburYe301
Counter-Strike
byalli539
x6flipin531
Heroes of the Storm
Khaldor238
Liquid`Hasu193
Other Games
FrodaN4939
B2W.Neo1844
Pyrionflax359
Fuzer 256
KnowMe216
DeMusliM40
Organizations
Dota 2
PGL Dota 2 - Main Stream14873
PGL Dota 2 - Secondary Stream1808
StarCraft 2
Blizzard YouTube
StarCraft: Brood War
BSLTrovo
sctven
[ Show 14 non-featured ]
StarCraft 2
• Adnapsc2 8
• Dystopia_ 6
• AfreecaTV YouTube
• intothetv
• Kozan
• IndyKCrew
• LaughNgamezSOOP
• Migwel
• sooper7s
StarCraft: Brood War
• BSLYoutube
• STPLYoutube
• ZZZeroYoutube
Dota 2
• WagamamaTV606
• Ler66
Upcoming Events
BSL 21
6h 6m
JDConan vs Semih
Dragon vs Dienmax
Tech vs NewOcean
TerrOr vs Artosis
IPSL
6h 6m
Dewalt vs WolFix
eOnzErG vs Bonyth
Replay Cast
9h 6m
Wardi Open
22h 6m
Monday Night Weeklies
1d 3h
Replay Cast
1d 9h
WardiTV Korean Royale
1d 22h
BSL: GosuLeague
2 days
The PondCast
2 days
Replay Cast
3 days
[ Show More ]
RSL Revival
3 days
BSL: GosuLeague
4 days
RSL Revival
4 days
WardiTV Korean Royale
4 days
RSL Revival
5 days
WardiTV Korean Royale
5 days
IPSL
6 days
Julia vs Artosis
JDConan vs DragOn
RSL Revival
6 days
Liquipedia Results

Completed

Proleague 2025-11-14
Stellar Fest: Constellation Cup
Eternal Conflict S1

Ongoing

C-Race Season 1
IPSL Winter 2025-26
KCM Race Survival 2025 Season 4
SOOP Univ League 2025
YSL S2
BSL Season 21
CSCL: Masked Kings S3
SLON Tour Season 2
RSL Revival: Season 3
META Madness #9
BLAST Rivals Fall 2025
IEM Chengdu 2025
PGL Masters Bucharest 2025
Thunderpick World Champ.
CS Asia Championships 2025
ESL Pro League S22
StarSeries Fall 2025
FISSURE Playground #2
BLAST Open Fall 2025

Upcoming

BSL 21 Non-Korean Championship
Acropolis #4
IPSL Spring 2026
HSC XXVIII
RSL Offline Finals
WardiTV 2025
IEM Kraków 2026
BLAST Bounty Winter 2026
BLAST Bounty Winter 2026: Closed Qualifier
eXTREMESLAND 2025
ESL Impact League Season 8
SL Budapest Major 2025
TLPD

1. ByuN
2. TY
3. Dark
4. Solar
5. Stats
6. Nerchio
7. sOs
8. soO
9. INnoVation
10. Elazer
1. Rain
2. Flash
3. EffOrt
4. Last
5. Bisu
6. Soulkey
7. Mini
8. Sharp
Sidebar Settings...

Advertising | Privacy Policy | Terms Of Use | Contact Us

Original banner artwork: Jim Warren
The contents of this webpage are copyright © 2025 TLnet. All Rights Reserved.