Skip to content Skip to sidebar Skip to footer

Visual C++ Using Cin to Read in a Cstring

C-style Strings in C++


By Alex Allain

In C++ in that location are two types of strings, C-style strings, and C++-style strings. This lesson will hash out C-style strings. C-style strings are really arrays, but there are some different functions that are used for strings, like adding to strings, finding the length of strings, and also of checking to see if strings match. The definition of a string would be anything that contains more than one character strung together. For example, "This" is a string. Nonetheless, single characters volition not exist strings, though they tin can be used as strings.

Strings are arrays of chars. String literals are words surrounded past double quotation marks.

"This is a static string"        

To declare a string of 49 messages, you would want to say:

char cord[50];        

This would declare a string with a length of 50 characters. Practise non forget that arrays begin at zero, not 1 for the alphabetize number. In addition, a cord ends with a null character, literally a '\0' character. However, simply recall that there volition be an actress character on the end on a string. It is like a menses at the finish of a sentence, it is not counted as a letter, just it however takes upward a space. Technically, in a fifty char array you could simply hold 49 letters and ane zilch graphic symbol at the end to terminate the string.

TAKE NOTE: char *arry; Can also be used as a string. If you have read the tutorial on pointers, you can do something such every bit:

arry = new char[256];        

which allows you to access arry just as if it were an array. Keep in heed that to use delete you must put [] between delete and arry to tell it to complimentary all 256 bytes of memory allocated.

For instance:

delete [] arry.        

Strings are useful for property all types of long input. If y'all want the user to input his or her name, yous must apply a string. Using cin>> to input a cord works, but it will terminate the string afterward it reads the showtime space. The best way to handle this situation is to utilize the role cin.getline. Technically cin is a form (a creature similar to a structure), and y'all are calling one of its fellow member functions. The most important thing is to understand how to use the function nonetheless.

The prototype for that office is:

istream& getline(char *buffer, int length, char terminal_char);        

The char *buffer is a pointer to the first element of the graphic symbol array, so that it tin can actually be used to access the array. The int length is simply how long the string to be input can be at its maximum (how big the array is). The char terminal_char ways that the string will stop if the user inputs whatever that character is. Keep in mind that it will discard whatever the terminal character is.

It is possible to brand a office call of cin.getline(arry, fifty); without the last character. Annotation that '\n' is the way of actually telling the compiler y'all mean a new line, i.e. someone hitting the enter key.

For a example:

#include <iostream>  using namespace std;  int main() {   char string[256];                               // A nice long string    cout<<"Please enter a long string: ";   cin.getline ( string, 256, '\n' );              // Input goes into string   cout<<"Your long string was: "<< cord <<endl;   cin.go(); }        

Remember that you are really passing the address of the array when you pass cord because arrays do not crave an accost operator (&) to be used to pass their address. Other than that, you could make '\due north' whatever character you desire (make sure to enclose it with unmarried quotes to inform the compiler of its graphic symbol status) to have the getline terminate on that grapheme.

cstring is a header file that contains many functions for manipulating strings. One of these is the string comparison function.

int strcmp ( const char *s1, const char *s2 );        

strcmp will accept two strings. It will return an integer. This integer volition either be:

Negative if s1 is less than s2. Zero if s1 and s2 are equal. Positive if s1 is greater than s2.        

Strcmp is example sensitive. Strcmp besides passes the address of the character assortment to the function to allow it to be accessed.

char *strcat ( char *dest, const char *src );        

strcat is curt for cord concatenate, which means to add to the end, or append. It adds the second cord to the first string. Information technology returns a arrow to the concatenated string. Beware this function, it assumes that dest is large enough to hold the entire contents of src every bit well as its own contents.

char *strcpy ( char *dest, const char *src );        

strcpy is curt for string copy, which means it copies the entire contents of src into dest. The contents of dest later strcpy will be exactly the same every bit src such that strcmp ( dest, src ) will return 0.

size_t strlen ( const char *southward );        

strlen will return the length of a cord, minus the terminating graphic symbol ('\0'). The size_t is aught to worry about. Just treat it every bit an integer that cannot exist negative, which it is.

Hither is a modest program using many of the previously described functions:

#include <iostream> //For cout #include <cstring>  //For the string functions  using namespace std;  int primary() {   char name[fifty];   char lastname[fifty];   char fullname[100]; // Big enough to hold both proper noun and lastname      cout<<"Please enter your name: ";   cin.getline ( name, l );   if ( strcmp ( name, "Julienne" ) == 0 ) // Equal strings     cout<<"That's my name besides.\n";   else                                    // Non equal     cout<<"That's not my name.\n";   // Notice the length of your proper noun   cout<<"Your proper noun is "<< strlen ( name ) <<" letters long\northward";   cout<<"Enter your last name: ";   cin.getline ( lastname, 50 );   fullname[0] = '\0';            // strcat searches for '\0' to cat after   strcat ( fullname, proper name );     // Copy name into total proper name   strcat ( fullname, " " );      // Nosotros want to separate the names past a infinite   strcat ( fullname, lastname ); // Copy lastname onto the end of fullname   cout<<"Your full name is "<< fullname <<"\n";   cin.get(); }        

Prophylactic Programming

The above string functions all rely on the being of a nix terminator at the end of a cord. This isn't always a safety bet. Moreover, some of them, noticeably strcat, rely on the fact that the destination string tin hold the entire string being appended onto the end. Although information technology might seem like you'll never make that sort of mistake, historically, bug based on accidentally writing off the end of an array in a office like strcat, accept been a major trouble.

Fortunately, in their infinite wisdom, the designers of C accept included functions designed to assistance yous avoid these issues. Similar to the way that fgets takes the maximum number of characters that fit into the buffer, there are cord functions that accept an additional argument to indicate the length of the destination buffer. For instance, the strcpy function has an coordinating strncpy function

char *strncpy ( char *dest, const char *src, size_t len );        

which will only copy len bytes from src to dest (len should be less than the size of dest or the write could still go beyond the bounds of the array). Unfortunately, strncpy can atomic number 82 to one picayune result: it doesn't guarantee that dest will have a null terminator attached to it (this might happen if the string src is longer than dest). Yous tin avoid this trouble by using strlen to get the length of src and make sure it will fit in dest. Of course, if you were going to exercise that, and then y'all probably don't demand strncpy in the get-go identify, right? Wrong. Now information technology forces yous to pay attention to this issue, which is a big part of the boxing.

Want to level up your game? Cheque this C++ IDE, from our sponsor

Quiz yourself
Previous: Arrays
Side by side: File I/O
Back to C++ Tutorial Index

montgomeryyoucity.blogspot.com

Source: https://www.cprogramming.com/tutorial/lesson9.html

Post a Comment for "Visual C++ Using Cin to Read in a Cstring"