菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
409
0

c++第十九天

原创
05/13 14:22
阅读数 52807

p109~p110:

 C风格字符串

特点:

1、不方便,不安全,尽量不使用。

2、必须以 '\0'结束。(只有这样才能使用C风格字符串函数)

3、一般利用指针操作这些字符。

4、可以用字符串字面值来初始化字符数组。

const char ca1[] = "A C-style character string";    // ca1其实是指向数组首元素的指针。

 

练习 3.37

这道题输出有点奇怪。。。

#include<iostream>
using std::cout;
using std::cin;
using std::endl;
int main()
{
    const char ca[] = {'h', 'e', 'l', 'l', 'o'};
    const char *cp = ca;
    while (*cp) {
        cout << *cp << endl;
        ++cp;
    }
    return 0;
}

输出结果:

D:\labs>a
h
e
l
l
o


a

 

练习 3.38

搬运。

Pointer addition is forbidden in C++, you can only subtract two pointers.

The reason for this is that subtracting two pointers gives a logically explainable result - the offset in memory between two pointers. Similarly, you can subtract or add an integral number to/from a pointer, which means "move the pointer up or down". Adding a pointer to a pointer is something which is hard to explain. What would the resulting pointner represent?

If by any chance you explicitly need a pointer to a place in memory whose address is the sum of some other two addresses, you can cast the two pointers to int, add ints, and cast back to a pointer. Remember though, that this solution needs huge care about the pointer arithmetic and is something you really should never do.

 

练习 3.39

1

#include<iostream>
using std::cout;
using std::cin;
using std::endl;
#include<cstring>
int main()
{
    const char ca1[] = "string-A";
    const char ca2[] = "string-B";
    if (strcmp(ca1 , ca2) > 0) {
        cout << "string-A big" << endl;
    } else {
        cout << "string-B big" << endl;
    }
    return 0;
}

 2

#include<iostream>
using std::cout;
using std::cin;
using std::endl;
#include<string>
using std::string;
int main()
{
    string s1 = "string-A";
    string s2 = "string-B";
    cout << "Big one is: ";
    if (s1 > s2) {
        cout << s1 << endl;
    } else {
        cout << s2 << endl;
    }
    return 0;
}

 

 练习 3.40

#include<cstring>
#include<iostream>
using std::cout;
using std::cin;
using std::endl;
int main()
{
    char s1[100] = "stringA";
    char s2[] = "stringB";
    strcat(s1 , s2);
    char s[100];
    strcpy(s , s1);
    cout << s << endl;
    return 0;
}

 

发表评论

0/200
409 点赞
0 评论
收藏
为你推荐 换一批