组合赋值运算符
操作符 | 作用(L作为左操作数,R为右操作数) |
+= | 将L+R赋给L |
-= | 将L-R赋给L |
*= | 将L*R赋给L |
/= | 将L/R赋给L |
%= | 将L%R赋给L |
文件尾条件
//一直读到文件的末尾才停止输入输出
#include
<iostream>
using
namespace
std;
int
main()
{
char
ch;
int
count = 0;
cin.get(ch);
do
{
cout
<<
ch;
count++;
cin.get(ch);
}
while
(cin.fail() ==
false
);
cout
<<
endl
<<
count
<<
"characters read\n"
;
//回车也要算上
return
0;
}
<ctrl>+<z>
<enter>
来模拟EOF条件
while
(cin.fail() ==
false
);
还可以更简单得改写成 while( !cin.fail() ) while( !cin.eof() )
更简便的可以while(cin)
字符函数库cctype
C++从C语言中继承了一个与字符相关的、非常方便的函数软件包,简化诸如确定字符是否为大写字母、数字、标点符号等工作,这些函数都是在cctype中定义的(老式的为ctype.h)
cctype中的字符函数
函数名称
|
返回值
|
isalnum( ) | 如果参数是字母数字,即字母或者数字,则函数返回为true |
isalpha( ) | 如果参数是字母,则返回值为true |
iscntrl( ) | 如果参数是控制字符,则返回值为true |
isdigit( ) | 如果参数是数字(0~9),则函数返回为true |
isgraph( ) | 如果参数是除空格之外的打印字符,则返回值为true |
islower( ) | 如果参数是小写字母,则返回值为true |
isprint( ) | 如果参数是打印字符(包括空格),则函数返回为true |
ispunct( ) | 如果参数是标点符号,则函数返回为true |
isspace( ) | 如果参数是标准空白字符,如空格、进纸、换行符、回车、水平制表符或者垂直制表符,则返回为true |
isupper( ) | 如果参数是大写字母,则函数返回为true |
isxdigit( ) | 如果参数是十六进制数字,即0~9,A~F,a~f,则函数返回为true |
tolower( ) | 如果参数是大写字符,则返回其小写,否则返回该参数 |
toupper( ) | 如果参数是小写字符,则返回其大写,否则返回该参数 |
使用这些函数比使用AND和OR运算符更方便;
if((ch >= 'a' &&ch <= 'z' || (ch >= 'A'&&ch <= 'Z' ));
与使用if(isalpha(ch));
相比,isalpha( )不仅更容易使用,而且更通用。
AND/OR格式假设A-Z的字符编码是连续的,其他字符的编码不在这个范围。这种假设对于ASCII是成立的,但通常并非如此。
(? : )条件运算符
它是C++中唯一一个需要三个操作数的运算符
expression1?expression2:expression3
如果expression1为true,则整个条件表达式的值取expression2,否则取expression3
例如:
int c=a>b?a:b;
其和
int c;
if(a>b)
c=a;
else
c=b;等价
对于文件的基本操作
/**@brief 实现先读取一个文本文档,然后统计其中字符、空格、换行符的个数
@praram 无
@return 无
*/
void
lq_fileio_demo()
{
using
namespace
std;
const
int
SIZE = 60;
char
filename[SIZE];
ifstream
infile;
//输入文件
cout
<<
"输入一个输入文件名:"
;
cin.getline(filename, SIZE);
infile.open(filename);
//将文件名和输入文件关联起来
if
(!infile.is_open())
{
cout
<<
"无法打开文件:"
<<
filename
<<
endl;
exit(
EXIT_FAILURE
);
}
//统计其中的字符数
char
ch;
uint
chars = 0, digits = 0, spaces = 0, puncts = 0, others = 0;
uint
lower = 0, upper = 0;
infile
>>
ch;
//得到第一个字符
while
(infile.good())
//没有到文件尾部
{
if
(isalpha(ch))
{
chars++;
islower(ch) ? lower++ : upper++;
}
else
if
(isdigit(ch))
digits++;
else
if
(isspace(ch))
spaces++;
else
if
(ispunct(ch))
puncts++;
else
others++;
infile
>>
ch;
//继续往后读取
}
//显示结果
cout
<<
chars
<<
"个字母;"
<<
lower
<<
"个小写字母,"
<<
upper
<<
"个大写字母\n"
<<
digits
<<
"个数字;\n"
<<
spaces
<<
"个空白字符;\n"
<<
puncts
<<
"个标点;\n"
<<
others
<<
"个其余字符;\n"
;
//输出到目标文件中
ofstream
outfile;
outfile.open(
"calnum.txt"
);
if
(infile.eof())
{
cout
<<
"已到到文件结尾\n"
;
}
else
if
(infile.fail())
{
cout
<<
"文件读取失败!\n"
;
}
else
cout
<<
"发生未知错误!\n"
;
outfile
<<
chars
<<
"个字母;"
<<
lower
<<
"个小写字母,"
<<
upper
<<
"个大写字母\n"
<<
digits
<<
"个数字;\n"
<<
spaces
<<
"个空白字符;\n"
<<
puncts
<<
"个标点;\n"
<<
others
<<
"个其余字符;\n"
;
}
由结果可知,读文件会跳过空格和回车,使得字符统计变得不准确,对于这个,之后的章节会有相应解决方法