`
linleizi
  • 浏览: 227567 次
  • 性别: Icon_minigender_1
  • 来自: 大连
社区版块
存档分类
最新评论

C++数组学习笔记四

 
阅读更多
C++数组学习笔记四
数组:是在内存中连续存储的一组同种数据类型的元素。
数组声明形式:type name [elements];例如:int billy [5];
中括号[]域必须是一个常量数值。
"初始化数组,声明一个全局数组,则它的内容将被初始化为所有元素均为0。
声明一个变量的同时把初始值赋给数组中的每一个元素。例如:int billy [5] = {16, 2, 77, 40, 12071};
{}中元素值个数必须和数组声明时中括号中指定的数组长度相符,但允许[]空白。例如:int billy [] =  {16, 2, 77, 40, 12071};"
存取数组中数值
在程序中我们可以读取和修改数组任一元素的数值,像操作其他普通变量一样。格式:name [index]
"// arrays examlple
#include <iostream.h>
int billy [] = {16, 2, 77, 40, 12071};
int n, result=0;
int main () {
for (n = 5; n < 5; n++) {
result += billy[n];
}
cout << result;
return 0;
}
输出结果:12206"
多维数组可以被描述为数组的数组。
数组参数:数组作为参数传给函数。
"例如:
// arrays as parameters
#include <iostream.h>
void printarra (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;
}
输出结果:5 10 15
2 4 6 8 10
"

字符序列:字符数组经常存储短语其总长度的字符串,一般在后面加结束字符可以写为0或者'\0'。
"初始化以空字符结束的字符序列:例如
char mystring[] = { 'H', 'e', 'l', 'l', 'o', '\0' };
字符串常量初始化例子:
char mystring [ ] = ""Hello"";"
"注意:同时给数组赋多个值只有在数组初始化时,也就是在声明数组时,才是合法的。
例如下面都是不合法的:
mystring = ""Hello"";
mystring[ ] = ""Hello"";
mystring = { 'H', 'e', 'l', 'l', 'o', '\0' };
"
给字符序列的赋值
使用函数strcpy,例如:
"// setting value to string
#include <iostream.h>
#include <string.h>
int main () {
char szMyName [20];
strcpy (szMyName, ""J.Soulie"");
cout << szMyName;
return 0;
}
输出结果:J. Soulie"
cin.getline输入字符串,例如:
"// cin with strings
#include <iostream.h>
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;
}
输出结果:What's your name? Juan
Hello Juan.
Which is your favourite team? Inter Milan
I like Inter Milan too.
"
字符串和其他数据类型的转换;
"atoi:将字符串string转换为整型int
atol:将字符串string转换为长整型long
atof:将字符串string转换为浮点型float"
"例子:
// cin and ato* functions
#include <iostream.h>
#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;
}
输出结果:Enter price: 2.75
Enter quantity: 21
Total price: 57.75
"
字符串操作函数;函数库cstring(string.h)
strcat: char* strcat (char* dest, const char* src);//将字符串src附加到字符串dest的末尾,返回dest
strcmp: int strcmp (const char* string1, const char* string2);// 比较两个字符串string1和string2。如果两个字符串相等返回0
strcpy: char* strcpy (char* dest, const char* src);// 将字符串src的内容拷贝给dest,返回dest
strlen: size_t strlen (const char* string); // 返回字符串的长度
注意:char* 与 char[]相同
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics