一 把数组作为参数
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)