-
C++第一天
今天是C++第一天,讲的都是基础内容,一天下来连基本的输入cin输出cout都没有使用熟练,再加上前面C基础不牢固,现在想用C++写一个简单的程序都有困难,追根究底还是代码量匮乏,没有养成程序员思维。今天在同学的帮助下让我的第一个项目取得了很大的进展,争取在这个假期里能让其正常运行起来。
cin输入:
#include <iostream>
using namespace std;
int main(void)
{
char caData[64] = {'\0'};
//遇到空格或者换行结束输入字符串
cin >> caData;
cout << caData << endl;
int iNum = 0;
float fData = 0.0f;
cin >> iNum >> fData;
cout << iNum << ' ' << fData <<endl;
return 0;
}
cout输出:
#include <iostream>
using namespace std;
int main(void)
{
cout << "HelloWorld\n";
//3.14:默认为double
//5.2f:f用来说明为float
cout << 3.14 << ' ' << 5.2f << '\n';
const char *p = "VeryGood";
cout << p << ' ' << (void*)p <<'\n';
cout << (void *)"VeryGood" << '\n';
cout << "VeryGood"[1] << '\n';
char caBuf[9] = "$TTYTTY$";
//endl --> '\n'
cout << caBuf << endl;
return 0;
}
namespace命名空间:
#include <iostream>
//命名空间:std
//命名空间相当于
//对不同的代码块分的不同的组
//using namespace std;
//自定义代码分组
//防止命名冲突
//便于代码管理
//使代码分类更简洁
namespace PROJECT_A
{
void fun()
{
std::cout << "A::FUN()\n";
}
}
namespace PROJECT_B
{
void fun()
{
std::cout << "B::FUN()\n";
}
}
int main(void)
{
PROJECT_B::fun();
std::cout << "hello" << std::endl;
return 0;
}
#if 0
using namespace PROJECT_A;
int main(void)
{
fun();
std::cout << "hello" << std::endl;
return 0;
}
#endif
冒泡排序:
#include <iostream>
using namespace std;
#define NUM 6
void bubble(int arr[NUM])
{
int i = 0;
int j = 0;
int tmp = 0;
for (; i < NUM-1; i++)
{
for (j = 0; j < NUM-1-i; j++)
{
if (arr[j] > arr[j+1])
{
tmp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = tmp;
}
}
}
}
int main(void)
{
int arr[NUM] = {0};
for (int i = 0; i < NUM; i++)
{
cout << "请输入第" << i << "个数据:";
cin >> arr[i];
}
bubble(arr);
for (int i = 0; i < NUM; i++)
{
cout << arr[i] << ' ';
}
cout << endl;
return 0;
}
指针:
#include <iostream>
using namespace std;
int main(void)
{
int a = 90;
int *p = &a;
*p = *p + 10;
cout << "a=" << *p << endl;
int* &ref = p;
*ref = *ref + 10;
cout << "a=" << *ref << endl;
cout << "a=" << a << endl;
return 0;
}
别名:
#include <iostream>
using namespace std;
//引用:类似于指针
//是变量的别名
//void myswap(int p1, int p2);
//void myswap(int *p1, int *p2);
void myswap(int &r1, int &r2)
{
int tmp = r1;
r1 = r2;
r2 = tmp;
}
int main(void)
{
int a = 90;
int b = 89;
cout << "a=" << a
<< " b=" << b << endl;
myswap(a, b);
cout << "a=" << a
<< " b=" << b << endl;
#if 0
int a = 90;
//int *pa = &a;
//*pa = 190;
//定义一个变量的别名
//对别名的操作即是对变量的操作
//引用必须初始化
int &ref = a;
cout << "a=" << a << endl;
cout << "ref=" << ref << endl;
cout << "&a=" <<(void*)&a
<< "&ref=" <<(void*)&ref
<< endl;
#endif
return 0;
}
结构体:
#include <iostream>
using namespace std;
typedef struct Test
{
int &a;
char &b;
double &c;
}Test;
int main(void)
{
cout << sizeof(Test) << '\n';
int aa = 90;
char bb = 'b';
double cc = 3.14;
Test t = {aa, bb, cc};
cout << "&aa=" << (void*)&aa<< endl;
cout << "&bb=" << (void*)&bb<< endl;
cout << "&cc=" << (void*)&cc<< endl;
cout << (void *)*((int *)&t) << endl;
cout << (void *)*((int *)&t+1) << endl;
cout << (void *)*((int *)&t+2) << endl;
return 0;
}
网友评论