for循环
与C语言几乎无大差别,存在的差别是C++可以这样写:
for(int i =0 ; i<20;i++)
{
}
基于范围的for循环
例如:
string word1 = "?ate";
for (char x : word1)
{
cout << x << endl;
}
//列表形式循环,多用于容器类
for (int t : {2, 3, 5, 6})
{
cout << t << endl;
}
说明:for中的word1表示word1数组第一元素开始,自加一,每一个元素给x输出
分支上:
C++与C几乎差别
字符函数库
函数 | 说明 |
---|---|
isalpha() | 判断是否为字母,是则为非零,不是则为零 |
ispunct() | 判断是否为标点符号,是则为非零,不是则为零 |
isalnum() | 判断是字母或数字,是则为true |
iscntrl() | 判断是控制字符,是则为true |
isdigit() | 判断是数字(0~9),是则为true |
isgraph() | 判断是除空格之外的打印字符,是则为true |
islower() | 判断是小写字母,是则返回true |
isprint() | 判断是打印字符(包括空格),则返回true |
isspace() | 判断是标准空白字符,如空格、换行符、回车、水平或垂直制表符,是则为true |
isupper() | 判断是大写字母,则返回true |
isxdigit() | 判断十六进制数,即0~9, a-f或A-F,是则返回true |
tolower() | 大写字符返回其小写 |
toupper() | 小写字符返回其大写 |
读取文本文件
(1)必须包含
#include<fstream>
#include<iostream>
必须申明 std 名称空间
引用 ifstream
类
#include <iostream>
#include<fstream>
using namespace std;
int main()
{
ifstream file;//定义个文件类型变量
file.open("C:/Users/Dell/Desktop/test.txt");//绝对路径
if (!file.is_open())
{
cout << "打开失败" << endl;
exit(EXIT_FAILURE);//结束程序
}
int counts = 0;
int value;
while (file.good())//在读取过程中没有出现异常情况则返回true
{
counts++;
file >> value;//取一个值
cout << counts << "+data:" << value<<endl;
}
}
输出:
1+data:12
2+data:13
3+data:14
4+data:15
5+data:16
6+data:17
7+data:18
8+data:19
9+data:20
注:
(1)一般判断出现EOF时,while跳出循环,也就是good()函数返回false。即就是没有任何数据可取时。
(2)回车字符 和 换行字符 作为分隔两数值的间隔作用
(3)函数 eof() 和 fail() 的作用分别是:
eof():检测EOF是否出现,出现则返回true;
fail():检测EOF和类型不匹配情况,出现则返回true;