C++的数组

一 把数组作为参数

1 代码

#include <iostream>
using namespace std;

void printarray(int arg[], int length) {
    for (int n = 0; n < length; n++) {
        cout << arg[n] << " ";
    }
    cout << "\n";
}

int main() {
    int firstarray[] = { 5, 10, 15 };
    int secondarray[] = { 2, 4, 6, 8, 10 };
    printarray(firstarray, 3);   // 实际传递的是数组的地址
    printarray(secondarray, 5);
    return 0;
}

2 运行

[root@localhost test]# g++ test.cpp -o test
[root@localhost test]# ./test
5 10 15
2 4 6 8 10

二 strcpy的简单使用

1 代码

#include <iostream>
using namespace std;
#include <string.h>
int main() {
    char szMyName[20];
    strcpy(szMyName, "J. Soulie");
    cout << szMyName << endl;
    return 0;
}

2 运行

[root@localhost test]# g++ test.cpp -o test
[root@localhost test]# ./test
J. Soulie

3 说明

strcpy(string1,string2);

string2可以是一个数组、一个指针或一个字符串常量。

三 通过cin输入字符数组

1 代码

#include <iostream>
using namespace std;
int main() {
    char mybuffer[100];
    cout << "What's your name? ";
    cin.getline(mybuffer, 100);
    cout << "Hello " << mybuffer << ".\n";
    cout << "Which is your favourite team? ";
    cin.getline(mybuffer, 100);
    cout << "I like " << mybuffer << " too.\n";
    return 0;
}

2 运行

[root@localhost test]# g++ test.cpp -o test
[root@localhost test]# ./test
What's your name? cakin24
Hello cakin24.
Which is your favourite team? star
I like star too.

3 说明

上面例子中两次调用cin.getline时,都使用了同一个字符串标识mybuffer。程序第二次调用时,新输入的内容将直接覆盖第一次输入buffer中的内容。

四 字符串转换

1 代码

#include <iostream>
using namespace std;
#include <stdlib.h>

int main() {
    char mybuffer[100];
    float price;
    int quantity;
    cout << "Enter price: ";
    cin.getline(mybuffer, 100);
    price = atof(mybuffer);
    cout << "Enter quantity: ";
    cin.getline(mybuffer, 100);
    quantity = atoi(mybuffer);
    cout << "Total price: " << price*quantity;
    return 0;
}

2 运行

[root@localhost test]# g++ test.cpp -o test
[root@localhost test]# ./test
Enter price: 5.7
Enter quantity: 4
Total price: 22.8

3 说明

atoi:将字符串转换为整型(int)

atol:将字符串转换为长整型(long)

atof:将字符串转换为浮点型(float)

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值