前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布

String

作者头像
青木
发布2018-05-28 15:40:52
6530
发布2018-05-28 15:40:52
举报

Strings

C-style strings have a special feature:The last character of every string is the null character .Consider the following two declarations:

代码语言:javascript
复制
char dog[8] = {'b','e','a','u','x',' ','I','I'};// not a string
char cat[8] = {'f','a','t','e','s','s','a','\0'}//a string

If you are ungracious enough to tell cout to display the dog array form the preceding example, which is not a string ,cout prints eight letters in the array and then keeps matching through memory byte-by-byte,interptreting each byte as a character to print, until it reaches a null character . There is a better way to initialize a character array to a string.Just use a quoted string,called a string constrant or string literal,as in the following:

代码语言:javascript
复制
char bird[11] = "Mr. Cheeps";    //the \0 is understood
 char fish[] = "Bubbles";            //let the compiler count

Quoted strings always include the terminating null character implicitly, so you don't have to spell it out. You should make sure the array is large enough to hold all the characters of the string,including the null character. Initializing a character array with a string constant is one case where it may be safer to let the compiler count the number of elements for you. There is no harm, other than wasted space,in making an array larger than the string.That's because functions that work with strings are guided by the location of the null character,not by the size of the array. C++ imposes to limits on the length of a string.

Caution When determining the minimum array size necessary to hold a string,remeber to include the terminating null character in your count.

Using Strings in an Array

The sizeof operator gives the size of the entire array. The strlen() functoin returns the size of the string stored in the array and not the size of the array itself.Also strlen() counts just the visible characters and not the null character. If cosmic is a string,the minimum array size for holding that string is strlen(cosmic)+1

Line-Oriented Input with getline()

The getline() function reads a whole line,using the newline character transmitted by the Enter key to mark the end of input. You invoke this method by using cin.getline() as a function call.

The function takes two arguments:

  • the first argument is the name of the target(that is,the array destined to hold the line of input)
  • the second argument is a limit on the number of characters to be read. If this limit is,say,20,the function reads no more than 19 characters,leaving room to automatically add the null character at the end. The getline() member function stops reading input when it reaches this numberic limit or when it reads a newline character,whichever comes first.

here is a example:

代码语言:javascript
复制
cin.getline(name,20);

The getline() function conventiently gets a line at a time.It reads input through the newline character marking the end of the line,but it does't save the newline character.Instead,it replaces it with a null character when storing the string.

Line-Oriented Input with get()

get() takes the same arguments,interprets them the same way,and reads to the end of a line.But rather than read and discard the newline character,get() leaves that character in the input queue.Suppose you use two calls to get() in a row.

代码语言:javascript
复制
cin.get(name,ArSize);
cin.get(dessert,ArSize);    //a problem

Because the first call leaves the newline character in the input queue,that newline character is the first character the second call sees. Thus,get() concludes that it's reached the end of line without having found anything to read.Without help,get() just can't get past that newline character. The call cin.get() (with) no arguments reads the single next character,even if it is a newline,so you can use it to dispose of the newline character and prepare for the next line of input.That is,this sequence workd:

代码语言:javascript
复制
cin.get(name,ArSize);    //read first line
cin.get();    //read newline
cin.get(dessert,ArSize); //read second line

Another way to use get() is to concatenate,or join,the two class member functions,as follows:

代码语言:javascript
复制
cin.get(name,ArSize).get();    //concatanete member functions

What makes this possible is that cin.get(name,ArSize) return the cin object,which is then used as the object that invokes the get() function. Similarly,the the following statement reads two consecutive input lines into the arrays name1 and name2;it's equivalent to making two separate calls to cin.getline();

代码语言:javascript
复制
cin.getline(name1,ArSize).getline(name2,ArSize);

In short,getline() is a little simpler to use,but get() makes error checking simpler.You can use either one to read a line of input,just keep the slightly different behaviors in mind.

Empty Lines and Other Problems

What happens after getline() or get() reads an empty line?The original practice was that the next input statement picked up where the last getline() or get() left off. However,the current practice called the failbit.The implications of this act are that further input is blocked,but you can restore input with the following command:

代码语言:javascript
复制
cin.clear();

Another potential problem is that the input string could be longer than the acclocated space.If the input is longer than the number of characters specified,both *getline()*and get() leave the remaining characters in the input queue. However,getline() additionally sets the failbit and turns off further input. #Mixing String and Numberic Input Consider the simple program:

代码语言:javascript
复制
#include<iostream>
using namespace std;

int main(void)
{
	cout<<"What year was your house built?\n";
	int year;
	cin >>year;
        //cin.get(); or cin.get(ch);
	cout<<"What is its street address?\n";
	char address[80];
	cin.getline(address,80);
	cout<<"Year built:"<<year<<endl;
	cout<<"Address:"<<address<<endl;
	cout<<"Done!\n";
	return 0;
}
/*
    You never get the opportunity to enter the address.The problem is that when    *cin* read the year,it leaves the newline generated by the Enter Key in the input    queue.                                    
    Then cin.getline() reads the newline as an empty line and assign a null string    to the address array.
    The fix is to read and discard the newline before reading the address.
 */

Introducing the string class

The ISO/ANSI C++98 Standard expanded the C++ library by adding a string class. To use the string class,a program has to include the string header file. The class definition hides the array nature of a string and lets you treat a string much like an ordinary variable.

You can use a string object in the same manner as a character array:

  • You can initialize a string object to a C-style string.
  • You can use cin to store keyboard input in a string object.
  • You can use cout to display a string object
  • You can use array notation to access individual characters strored in a string obeject.

Assignment,Concatenation,and Appending

You can assign one string object to another:

代码语言:javascript
复制
char charr1[20];
char charr3[20] = "jaguar";
string str1;
string str2 = "panther";
charr1 = charr2; //Invalid,no array assignment
str1 = str2;  //valid,object assignment ok

The string class simplifies combining strings.You can use the + operator to add two string objects together and the += operator to tack on a string to the end of an existing string object.

代码语言:javascript
复制
string str3;
str3 = str1 + str2;
str1 += str2;

More string Class Operations

You can use the strcpy() funtion to copy a string to a character array,and you can use the strcat() function to append a string to a character array:

代码语言:javascript
复制
strcpy(charr1,charr2); //copy charr2 to charr1
strcat(charr1,charr2); //append contents of charr2 to charr1

The C library does provide cousins to strcat() and strcpy(),called strncat() and strncpy() ,that work more safely by taking a third argument to indicate the maximum allowd size of the target array,but using them adds another layer of complexity in writing programs.

More on string Class I/O

This is the code for reading a line into an array:

代码语言:javascript
复制
cin.getline(charr,20)

The dot notation indicates that the getline() function is a class method for the istream class.The first argument indicates the destination array,and the second argument is the array size,which getline() used to avoid overrunning the array. This is the code for reading a line into a string object:

代码语言:javascript
复制
getline(cin,str);

There is no dot notation,which indicates that this getline() is not a classmethod.So it takes cin as an argument that tells it where to find the input.Also there isn.t an argument for the size of the string because the string object automatically resizes to fit the string.

Other Forms of String Literals

C++ uses the L,u,and U prefixes,respectively,for string literals of these types.kHere is an example of how they can be used:

代码语言:javascript
复制
wchar_t title[] = L"Chief Astrogator";//w_char string
char16_t name[] = u"Felonia Ripova"; //char_16 string
char32_t car[] = U"Humber Super Snipe";//char_32 string
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Strings
  • Using Strings in an Array
  • Line-Oriented Input with getline()
  • Line-Oriented Input with get()
  • Empty Lines and Other Problems
  • Introducing the string class
  • Assignment,Concatenation,and Appending
  • More string Class Operations
  • More on string Class I/O
  • Other Forms of String Literals
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档