文章目录
- hello,world
- getline
- std::cin
- 引用与指针
- 函数
- 参考文献
hello,world
#include <iostream>using namespace std;int main()
{cout << "Hello world!" << endl;return 0;
}
getline
成员函数getline()是从输入流中读取一行字符,读到终止符时会将’\0’存入结果缓冲区中 [4],作为输入的终止。终止符可以是默认的终止符,也可以是定义的终止符。函数的语法结构是:
getline(<字符数组chs>,<读取字符的个数n>,<终止符>)
#include <iostream>using namespace std;int main()
{string name;string welcomeMessage;cout << "Hello world!" << endl;cin>>name;cout << "Hi!" <<name<< endl;getline(cin,welcomeMessage,'#');cout<<welcomeMessage<<endl;return 0;
}
Hello world!
lisi
Hi!lisi
you are good student!
#you are good student!Process returned 0 (0x0) execution time : 11.410 s
Press any key to continue.
std::cin
可同时接收多个数据输入,每个数据用空格分隔!
Hello world!
name age
lisi 29
Hi!lisi 29Process returned 0 (0x0) execution time : 3.817 s
Press any key to continue.
#include <iostream>using namespace std;int main()
{string name;int age;int temp;string welcomeMessage;cout << "Hello world!" << endl;cout<<"name age"<<endl;cin>>name>>age;cout << "Hi!" <<name<<" "<<age<<endl;return 0;
}
引用与指针
- 标量
100
100
88
99Process returned 0 (0x0) execution time : 1.819 s
Press any key to continue.
#include <iostream>using namespace std;int main()
{int a;int &a1=a;int *a2=&a;cin>>a;cout<<a<<endl;a1=88;cout<<a<<endl;*a2=99;cout<<a<<endl;return 0;
}
- 数组指针
#include <iostream>using namespace std;int main()
{int a[]{1,2,3,4,5,6,7,8};int *s=a;for (int *p=a;p<s+8;p++){cout<<p<<":"<<*p<<endl;}
}
#include <iostream>using namespace std;int main()
{int a[]{1,2,3,4,5,6,7,8};for (int *p=a;p<a+8;p++){cout<<p<<":"<<*p<<endl;}
}
1
2
3
4
5
6
7
8Process returned 0 (0x0) execution time : 0.126 s
Press any key to continue.
- 数组的引用
下面的程序是错误的
#include <iostream>using namespace std;int main()
{int a[]{1,2,3,4,5,6,7,8};for (int (&p)[8]=a;p<a+7;p++){cout<<*p<<endl;}}
错误如下
正确的写法只能如下:
#include <iostream>using namespace std;int main()
{int a[]{1,2,3,4,5,6,7,8};int (&p)[8]=a;for (int i=0;i<8;i++){cout<<p[i]<<endl;}
}
如果一定要用指针,只能考虑另外使用一个指针变量了,因为引用指向的内容可以更改,但引用本身的指向是不能更改,只读的。
#include <iostream>using namespace std;int main()
{int a[]{1,2,3,4,5,6,7,8};int (&p)[8]=a;for (int *p1=p;p1<a+8;p1++){cout<<*p1<<endl;}
}
函数
#include <iostream>using namespace std;void goThrough(int (&arr)[8]){for (int *p1=arr;p1<arr+8;p1++){cout<<*p1<<endl;}
}
int main()
{int a[]{1,2,3,4,5,6,7,8};goThrough(a);
}
更改数组元素
#include <iostream>using namespace std;void goThrough(int (&arr)[8]){for (int *p1=arr;p1<arr+8;p1++){cout<<*p1<<endl;}for (int *p1=arr;p1<arr+8;p1++){*p1*=10;}for (int *p1=arr;p1<arr+8;p1++){cout<<*p1<<endl;}
}
int main()
{int a[]{1,2,3,4,5,6,7,8};goThrough(a);
}
1
2
3
4
5
6
7
8
10
20
30
40
50
60
70
80Process returned 0 (0x0) execution time : 0.130 s
Press any key to continue.
参考文献
1、learn.microsoft.com
2、百度百科之geline