一、基本控制结构
ISO/ANSI C++中的控制与循环全部适用于C++/CLI。下例展示了C++/CLI控制台程序中的控制循环:
例子:基本循环控制
// Ex3_15.cpp : main project file. #include "stdafx.h" using namespace System; int main(array<System::String ^> ^args) { wchar_t letter; Console::Write(L"Enter a letter:"); letter = Console::Read(); if(letter>='A') if(letter<='Z') { Console::WriteLine(L"You entered a captial letter."); return 0; } if(letter>='a') if(letter<='z') { Console::WriteLine(L"You entered a small letter."); return 0; } Console::WriteLine(L"You did not enter a letter."); return 0; }
letter被声明为wchar_t类型,映射为C++/CLI中的System::Char类型,它具有一些特殊的功能,其中包括将字符代码转换为大写和小写的函数:Char::ToUpper()和Char::ToLower(),被转换的函数作为参数被传递给它:
wchar_t uppercaseLetter = Char::ToUpper(letter);
此外还包括检测字母是否大写或小写的函数:IsUpper()和IsLower(),因此上例可改为
wchar_t letter; wchar_t upper; Console::Write(L"Enter a letter:"); letter = Console::Read(); upper = Char::ToUpper(letter); if(upper>='A' && upper<='Z') Console::WriteLine(L"You entered a {0} letter.", Char::IsUpper(letter) ? "Capital":"Small"); else Console::WriteLine(L"You entered a small letter.");
Console::ReadKey()函数用于测试按键,并将结果存储在ConsoleKeyInfo类对象里。该类有3个可访问属性用于帮助确定被按下 的键是哪个或哪些键。属性Key识别被按下的键是哪个,属性KeyChar是被按键的Unicode字符码,属性Modifiers表示 Shift,Alt,Ctrl键的按位组合,它是定义在System命名空间中的枚举类型ConsoleModifiers的常量,包括 Shift\Alt\Control。
应该注意的是,在C++/CLI中枚举常量在用作数值之前必须被显示的强制转换为值类型(整数类型)
例子:使用Console::ReadKey()函数
// Ex3_16.cpp : main project file. #include "stdafx.h" using namespace System; int main(array<System::String ^> ^args) { ConsoleKeyInfo keyPress; Console::WriteLine(L"Press a key combination - press Escape to quit."); do{ keyPress = Console::ReadKey(true); Console::Write(L"You pressed"); if(safe_cast<int>(keyPress.Modifiers)>0) Console::Write(L" {0}", keyPress.Modifiers); Console::WriteLine(L" {0} which is the {1} character", keyPress.Key, keyPress.KeyChar); }while(keyPress.Key != ConsoleKey::Escape); return 0; }
该程序的输入示例如下:
Press a key combination - press Escape to quit. You pressed Enter which is the character You pressed Spacebar which is the character You pressed Spacebar which is the character
从输出中可以看出,当不只一个键被按下时,用一条语句就可以得到所有的键。这是因为Modifiers枚举类型是用FlagsAttribute属性定义 的,该属性表明这种枚举类型是一组唯一的位标志。这使得该枚举类型的变量可以由若干与在一起的标志位组成,而Write()或WriteLine()函数 可以识别并输出各标志位。
二、for each循环
以例子开始
// Ex3_17.cpp : main project file. #include "stdafx.h" using namespace System; int main(array<System::String ^> ^args) { int volwels = 0; int consonants = 0; String^ proverb = L"A nod is as good as a wink to a blind horse."; 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': ++volwels; break; default: ++consonants; break; } } } Console::WriteLine(proverb); Console::WriteLine(L"The proverb contains {0} volwels and {1} consonants.", volwels, consonants); return 0; }
输出为:
A nod is as good as a wink to a blind horse.
The proverb contains 14 volwels and 18 consanants.
注意:由于proverb字符串中的字符都是Unicode字符,因此用wchar_t(映射为Char类型)类型的变量来存储这些字符。变量ch为循环内的局部变量。