php 小企业网站 cms,军事新闻最新消息军事新闻,微信调用wordpress,怎么注册网上店铺本文主要内容为C下的输入输出函数以及for循环中的C11新特性。 一、输入输出函数
1. cin
cin 遇到 空格、回车、Tab结束输入#xff0c; 且会将读到的空格、回车、Tab 丢弃#xff0c;例#xff1a;
#includeiostream
using namespace std;int main(void) {char a…本文主要内容为C下的输入输出函数以及for循环中的C11新特性。 一、输入输出函数
1. cin
cin 遇到 空格、回车、Tab结束输入 且会将读到的空格、回车、Tab 丢弃例
#includeiostream
using namespace std;int main(void) {char a[10];cin a;cout a endl; //第一次输出cin a;cout a endl; //第二次输出return 0;
}
Test: 由图像可见在输入时若输入两串字符即便程序需要输入两次第二次读取不会再次手动从键盘输入而是上次输入的空格后的内容成为第二次读入的字符串。类似于scanf。 2. cin.get()
1) cin.get()有三种形式 ch cin.get(); cin.get( ch ); cin.get( str, size ); 注前两个用于读取字符第三个用于读取字符串。cin.get()不会丢弃读到的空格、回车即第一个cin.get()读到 Space 或 Enter 后停止读取数据在第二次的cin.get()中会将上次读取到的 Space 或 Enter 存到字符中而不是继续读取结束符后面的数据。
#includeiostream
using namespace std;int main(void) {char a, b, c;cout input: ; cin.get(a);cout output : a endl;cout input again: ;cin.get(b);cout output : b endl;cout input again: ;cin.get(c);cout output : c endl;return 0;
}
Test: 2) 在使用cin.get(str, size)读取字符串时同样会遇到Space与Enter结束输入而且不会将最后读到的Space与Enter丢弃所以会造成后续cin.get()无法继续读入应有的字符串。PS可用cin.clear()来清除
#includeiostream
using namespace std;int main(void) {char a[10], b[10], c[10];cout input: endl; cin.get(a, 10);cout output : a endl;cout input again: endl;cin.get(b, 10);cout output : b endl;cout input again: endl;cin.get(c, 10);cout output : c endl;return 0;
}
Test 3. cin.getline()
cin.getline(str, size);用于读取一行字符串限制读入size - 1个字符会自动将读到的Enter丢弃且会在字符串最后添加\0作为结束符。然而如果一行字符串长度超过 size 会造成多余字符丢失。 #includeiostream
using namespace std;int main(void) {char a[3], b[3], c[3];cin.getline(a, 3);cin.getline(b, 3);cin.getline(c, 3);cout output : a endl;cout output : b endl;cout output : c endl;return 0;
}
Test : 图中两次运行程序均只输入了一次第一次输入abcdefg测试长度超限第二次测试空格对其影响。二、循环C11 新特性
C11新增了一种循环基于范围range-based的for循环。 吐槽一下虽然在学C但是总是会想到Python因为好多东西貌似Python……就比如这个range-basedPython的循环为for i in range(1. 10) 遍历1 i 10
ok开始正题 1遍历
#includeiostream
using namespace std;int main(void) {int number[5] {3, 2, 1, 5, 4};cout Output : endl;for(int x : number) //warning: 此处为 而不是 ;cout x ;cout endl;return 0;
}for循环的含义为变量x在数组number中遍历且x代表数组中被指向的元素
Test 2修改数组元素
#includeiostream
using namespace std;int main(void) {int number[5] {3, 2, 1, 5, 4};for(int x : number)x * 2; //将数组中每个元素乘2cout Output : endl;for(int x : number)cout x ;cout endl;return 0;
}for循环中定义了x表明x为引用变量即改变x的值可以直接改变数组中对应元素的值。
Test 3for循环与初始化列表的结合
#includeiostream
using namespace std;int main(void) {cout Output : endl;for(int x : {5, 4, 1, 2, 3})cout x ;cout endl;return 0;
}x将遍历列表{5, 4, 1, 2, 3}中的值
Test 本次的笔记一暂时到此为止如有不足会持续更新、添加。