String handling in C++

Question:
What is the best way to manipulate strings in C++?

Answer:
Here is an example.

#include void foo (char *instring){	// Declare char array big enough to read in input	char read_string[80];	cin.readline(read_string,80);	if(strcmp(read_string,instring) == 0) // strcmp returns 0 if the strings										  // match 	{		// do something	}	else	{		// strings do not match	}}
The above approach will work, but it needs a lots more code to make it reallyrobust, e.g. what if the instring was sent in as null, or what if it was 80 chars in length, etc.

So to avoid these commonly occurring problems it is best to use some kindof String class to do all of your string processing. Almost all compilervendors include a String class with their implementations. String classes provide methods and operators to construct, assign, copy, read and write tostreams and many more operations.

Here’s how the above example would look if I had used the STL string classinstead of char arrays and pointers:

#include #include void foo(const string & instring){	string read_string; // construct a string object	cin >> read_string;	if (instring == read_string)		// .. do something else		//… do something else.}

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS