首页 > 代码库 > 第三章 判断和循环

第三章 判断和循环

选择语句

else总是属于前面最近的还没有对应else的if

switch格式

switch (choice)

{

 case choice1:...; break;

 case choice2:...; break;

 ...

 default:

}

可以不要default那么如果不匹配默认不执行break如果没有则默认一直往下执行如果在casse中创建变量那么必须用{}把case语句括起来可以case 1: case 2:这样共享case1和case 2的动作

循环语句

无穷循环

for(;;)

空的执行语句

for(int i=1;i<=max;sum+=i)

;

输出十六进制数

cout<<hex<<16<<"\t"<<dec<<16<<endl;

结果10     16

注将hex操作插入cout流时后面的整数以16进制输出

C++/CLI编程

Char::ToUpper()和Char::ToLower():转换wchar_t类型的大小写

Char::IsUpper()和Char::IsLower():判断wchar_t类型的大小写返回布尔值

Char::IsLetter()判断是否是字母

ConsoleKeyInfo有3个属性判断按下的是那个或者那些键

1.属性key标识被按下的那个键 

2.属性Modifiers标识按下的组合键中的ShiftAltCtrl 

3.KeyChar标识被按下键或者组合键的Unicode字符代码

程序

Console::WriteLine(L"press a key combination,press Escape to quit.");

ConsoleKeyInfo KeyPress;

do

{

Console::Write(L"press enter a key: ");

KeyPress=Console::ReadKey(true);

Console::WriteLine();

Console::Write(L"you press ");

if(safe_cast<int>(KeyPress.Modifiers)>0)

Console::Write(L"{0},",KeyPress.Modifiers);

Console::WriteLine(L"{0} which is {1} character",KeyPress.Key,KeyPress.KeyChar);

}while(KeyPress.Key!=ConsoleKey::Escape);

Console::ReadLine();

    return 0;

结果

press a key combination,press Escape to quit.

press enter a key:

you press A which is a character

press enter a key:

you press Control,A which is character

press enter a key:

you press Alt, Shift, Control,A which is 

for each循环

用于处理一组特定对象中的所有对象

比如

String对象由一组字符对象组成所以可以用for each处理

程序计算输入的原音和辅音数目

int vowels(0),consonants(0);

String^ proverb;

Console::Write(L"press enter some words: ");

proverb=Console::ReadLine();

for each(wchar_t ch in proverb)

{

if(Char::IsLetter(ch))

{

ch=Char::ToLower(ch);

switch(ch)

{

case ‘a‘:case ‘e‘:case ‘i‘:case ‘o‘:case ‘u‘:

++vowels;

break;

default:

++consonants;

break;

}

}

}

Console::WriteLine(L"there are {0} vowels and {1} consonants in {2}",vowels,consonants,proverb);

Console::ReadLine();

    return 0;

结果

press enter some words: a nod is as good as a wink to a blind horse

there are 14 vowels and 18 consonants in a nod is as good as a wink to a blind horse


本文出自 “flyclc” 博客,请务必保留此出处http://flyclc.blog.51cto.com/1385758/1540144