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

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:

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:


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.

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:

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:

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();


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:


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:

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];
	cout<<"Year built:"<<year<<endl;
	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:

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.

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:

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:


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:


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:

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



0 条评论
登录 后参与评论


  • The Address of an Array

  • Pointer and the C++ Philosophy

  • redis_3.0.7_sds.c_sdsull2str()

  • Codeforces Round #345 (Div. 2)【A.模拟,B,暴力,C,STL,容斥原理】

    A. Joysticks time limit per test:1 second memory limit per test:256 megabytes in...

  • 统计学中的区间估计

    统计学中有两大分支——描述性统计学(description stats)和推断性统计学(inference stats)。 推断性统计学中,很重要的一点就是...

  • Oops错误

    在at91rm9200下写了一个spi的驱动,加载后,运行测试程序时,蹦出这么个吓人的东西: Unable to handle kernel paging r...

  • 循环热管的动态状态空间建模与基于模型的控制设计(CS SY)


  • Unity-UI(UGUI详解)01基础概念、自动布局、动画集成、富文本

    Canvas应该包含全部UI元素,全部的UI元素应该时Canvas的子物体 调整元素的显示顺序可以从Hierarchy中直接拖拽他们,顺序从也可以被控制通过S...

  • WashU EpiGenome Browser使用教程

    WashU EpiGenome Browser 是我用过最赞的浏览器,没有之一。希望大伙跟着教程好好学习下! 还有更多教程见:http://epigenomeg...

  • 机器学习实战(二) - 单变量线性回归Model and Cost Function1 模型概述 - Model Representation2 代价函数 - Cost Function3 代价函数(

    To establish notation for future use, we’ll use