C ++ character (char) pointer

In the last chapter , the detailed account of the ordinary pointers one-dimensional array of usage, now tell us about the character pointer

If not you want to see content, you can see: Pointer directory

char pointer fashion statement is consistent with the general pointer, but there are some special place

char pointer can be seen as a string , for example:

const char *str="HelloWorld!";

If const unfamiliar, can be seen here

To create a string pointer, the above is a - and I also suggested that the application space, freeing up space in the standard pointer operation

For example, here:

#include <iostream>
#include <cstring>
using namespace std;
int main()
{
    char *str=new char[101];
    cin>>*str;
    cout<<*str<<endl;
    delete[] str;
    return 0;
}

Now the question is

Input :

TweeChalice


Output :

T

Have you ever thought how could this happen? ------ If you can not think, read again, C ++ pointer with one-dimensional arrays

 

 

After reading the last chapter, we already know that the array is a continuous space

 

And how did we enter?

cin>>*str;

This input is str [0], the following input omitted entirely

And how can we output?

cout<<*str;

This output is str [0]

 

Now you know how it is, right!

But how we want to enter a char pointer it?

 

Since they fully adopted the C-style pointers, then I recommend two functions from the header files <cstring>

If there are syntax based should know:

gets 与 puts

Performance function must be very familiar not introduced, direct look at the code:

#include <iostream>
#include <cstring>
using namespace std;
int main()
{
    char *str=new char[101];
    gets(str);
    puts(str);
    delete[] str;
    return 0;
}

This time the problem is solved, but if we input and output normal little imagination, does not monitor line, look at the space ( like cin, cout , then recommend <cstring> in getchar ()

We can write:

#include <iostream>
#include <cstring>
using namespace std;
int main()
{
    char *str=new char[101];
    int i=0;
    while(true)
    {
        *(str+i)=getchar();
        if(*(str+i)==' '||*(str+i)=='\n')
            break;
        i++;
    }
    for(int j=0;j<i;j++)
        cout<<*(str+j);
    delete[] str;
    return 0;
}

The code is too big , it is recommended that you use string or char array

 

After reading the recommendation to the next chapter: Pointer and n-dimensional arrays

Recommend See C ++ pointer directory

Guess you like

Origin www.cnblogs.com/tweechalice/p/11441421.html