You are here:

C++/strings in c++

Advertisement


Question
hi!


Q how can i compare two user entered strings??using strcmp()???
and besides strcmp() is there any other way because this way i have to use pointers as in prog  below.....

i have tried to make 2D array to store information.
my prog makes a new array equal to a user entered no....
and then checks whether the aacnt no user has entered  already  exists or not......

this is a part of it:

explain to me the comparison part as i have to use it extensively......

int t;

 char *accntno[10];
 char **accounts;
cout<<"Enter no of accounts"<<endl;
cin>>t;

for(int f=0;f<t;f++)
{
accounts=new char *[f];
for(int j=0;j<6;j++)
*accounts=new char[j];
}
cin>>accounts[4][0];
cin>>accntno[10];

now for comparison:
int x =4;   
int y= (strcmp(accounts[x][0],accntno[10]));
}  

Answer
You used the subject "strings in c++"

What you are actually trying to do is "strings in C"

The fact that C++ 'inherits' these features of C is true of course but ISO standard C++ (hosted version) includes string support as user defined types in the standard C++ library.

So assuming you have a C++ compiler and library produced within the last 10 years and are not using a non-hosted version for system or embedded work, then you almost certainly have access to these facilities.

C strings are _not_ pointers to char - a pointer is just a reference to some memory location containing data of a specific type. C strings are arrays of char in which the last character is of zero value ('\0') to signal the end of the string.

In C (and thereby C++) the name of a built in array is equivalent to the address of the first element of the array - i.e.: saying:

   MyArray

is equivalent to:

   &MyArray[0]

where the unary & operator used here means "address of".

Hence it is common and usual to pass array data by pointer, thus:

   char str1[] = {'a','b','c', '\0' };    
   char str2[] = {'a','b','d', '\0' };
   
   if ( strcmp(str1, str2)==0 )
   {
       std::cout << "str1 equals str2\n";
   }
   else if ( strcmp(str1, str2)<0 )
   {
       std::cout << "str1 less than str2\n";
   }
   else
   {
       std::cout << "str1 greater than str2\n";
   }

is perfectly valid. You will notice the form of strlen usage: we provide 2 C strings, it compares them and returns zero if they are equal, a less than zero value if str1 is lexicographically less then str2, and a greater than zero value if str1 is lexicographically greater then str2: this information you can obtain from any decent C library reference, any maybe some C++ library references although some C++ references may not go into details of C library features!

Notice that I arranged for both space for the characters in the C strings _and_ that this space contained valid data _before_ passing the C strings to strcmp - which from its declaration seems to require constant pointers to char as arguments. This is because:

   str1 is equivalent to &str1[0]
   str2 is equivalent to &str2[0]

As to the difference between pointers to constant and non constant data - as we are passing a pointer to non constant data to a function that just requires constant access to the data this is OK - it is very much like saying the function only needs read access to the data and not read/write access, as we have pointers that allow read/write access to the data - which is a superset of the function parameter requirements - this is OK.

The main problem with your code is that you seem to get horribly confused allocating the data for the C strings. I am lost at what you are trying to do with new [] in the for f loop - you seem to be allocating array of pointers to char with f elements where f varies from 0 to t and then for each f value allocate array of char with j elements where j ranges from 0 to 5 each time. Each time around the loop you overwrite the accounts pointer to the char * array - so all previous such arrays and the char arrays _they_ point to are orphaned - you have no way to access them (and therefore the memory they used cannot be reclaimed as you have no way to delete it - i.e. you have a memory leak).

So I suggest instead that you make use of the C++ standard library std::string type instead as this type takes care of the resource management for you and provides a much easier to use interface. You should include <string> (no extension) to use std::string.

For example you can read a line of text into a std::string from the console input stream like so:

   #include <string>
   #include <iostream>

   // ...

   std::string inputString;
   
   std::getline(std::cin, inputString);

Two std::strings can be compared for equality like so:

   if ( inputString == someOtherString )
   {
       std::cout << "You entered a duplicate of the other string\n";
   }

You can have a built in array of std::strings:

   unsigned int const MaximumReadStrings(10);

   // ...

   std::string readStrings[MaximumReadStrings];

You can of course check such an array for duplicates:

   bool is_unique(true);
   for ( unsigned int i=0; i != numberOfStringsRead; ++i )
   {
       if ( inputString == readStrings[i] )
       {
         std::cout << "You entered a duplicate of a previously entered string\n";
         is_unique = false;
         break;
       }
   }

   if ( is_unique )
   {
       readStrings[numberOfStringsRead++] = inputString;
   }

In order for your original code to work you would have to have done something like so:

   #include <cstring>
   #include <iostream>

   // ...

   unsigned int const MaximumStringLength(255);
   unsigned int const StringBufferSize(MaximumStringLength+1); // +1 for terminating '\0'
   unsigned int const MaximumReadStrings(10);

   // ...

   char inputString[StringBufferSize];
   char readStrings[MaximumReadStrings][StringBufferSize]; // array of MaximumReadStrings arrays of StringBufferSize chars

   // ...

   std::cin.getline(inputString, StringBufferSize);

   // ...

   bool is_unique(true);
   for ( unsigned int i=0; i != numberOfStringsRead; ++i )
   {
       if ( strcmp(inputString,readStrings[i])==0 )
       {
         std::cout << "You entered a duplicate of a previously entered string\n";
         is_unique = false;
         break;
       }
   }

   if ( is_unique )
   {
       strcpy(readStrings[numberOfStringsRead++], inputString);
   }

Which uses fixed sized arrays of char for the string storage, and probably therefore wastes some space, but does not require any dynamic memory management. To allocate exactly the required amount of space for each string in readStrings we would modify the above like so:

   char * readStrings[MaximumReadStrings]; // array of MaximumReadStrings of char *

   // ...

   if ( is_unique )
   {
   // Allocate exactly the number of chars we require for this string
   // Be aware: new [] can fail, throwing a std::bad_alloc exception
       readStrings[numberOfStringsRead] = new char[strlen(inputString)+1];
       strcpy(readStrings[numberOfStringsRead++], inputString);
   }

   // ...

   // ** must explicitly release resources dynamically allocated and created **
   for ( unsigned int i=0; i != numberOfStringsRead; ++i )
   {
       delete [] readStrings[numberOfStringsRead];
   }

The above code snippets show quite a bit of what you seem to be trying to do. You will have to add some bits around these snippets to produce a full program.

I suggest you get yourself a decent reference for the C++ standard library such as "The C++ Standard Library A Tutorial and Reference" by Nicolai M. Josuttis.

None of the code has been tested - it comes straight out of my head - so I apologise now for any errors or typos! Sorry.

Hope this helps, and please ask a followup question if you require further help on any points.  

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Ralph McArdell

Expertise

I am a software developer with more than 15 years C++ experience and over 25 years experience developing a wide variety of applications for Windows NT/2000/XP, UNIX, Linux and other platforms. I can help with basic to advanced C++, C (although I do not write just-C much if at all these days so maybe ask in the C section about purely C matters), software development and many platform specific and system development problems.

Experience

My career started in the mid 1980s working as a batch process operator for the now defunct Inner London Education Authority, working on Prime mini computers. I then moved into the role of Programmer / Analyst, also on the Primes, then into technical support and finally into the micro computing section, using a variety of 16 and 8 bit machines. Following the demise of the ILEA I worked for a small company, now gone, called Hodos. I worked on a part task train simulator using C and the Intel DVI (Digital Video Interactive) - the hardware based predecessor to Indeo. Other projects included a CGI based train simulator (different goals to the first), and various other projects in C and Visual Basic (er, version 1 that is). When Hodos went into receivership I went freelance and finally managed to start working in C++. I initially had contracts working on train simulators (surprise) and multimedia - I worked on many of the Dorling Kindersley CD-ROM titles and wrote the screensaver games for the Wallace and Gromit Cracking Animator CD. My more recent contracts have been more traditionally IT based, working predominately in C++ on MS Windows NT, 2000. XP, Linux and UN*X. These projects have had wide ranging additional skill sets including system analysis and design, databases and SQL in various guises, C#, client server and remoting, cross porting applications between platforms and various client development processes. I have an interest in the development of the C++ core language and libraries and try to keep up with at least some of the papers on the ISO C++ Standard Committee site at http://www.open-std.org/jtc1/sc22/wg21/.

Education/Credentials

©2016 About.com. All rights reserved.