#include <iostream>
#include <string>
int main()
{
using namespace std;
cout << "Enter a word: ";
string word;
cin >> word;
// display letters in reverse order
for (int i = word.size() - 1; i >= 0; i--)
cout << word[i];
cout << "\nBye.\n";
// cin.get();
// cin.get();
return 0;
}
该函数展示了使用for依次访问字符串中每个字符的方式
该函数使用了string对象
string类的size()是用来获得字符串中的字符数
从最开始的word【i-1】开始,使用i--反向计数,依次取值
5.7 plus_one.cpp
#include <iostream>
int main()
{
using std::cout;
int a = 20;
int b = 20;
cout << "a = " << a << ": b = " << b << "\n";
cout << "a++ = " << a++ << ": ++b = " << ++b << "\n";
cout << "a = " << a << ": b = " << b << "\n";
// std::cin.get();
return 0;
}
该函数展示了a++与++a的区别
a++意味着先使用a的值计算表达式,然后再+1,而++b则是先+1,再使用b的值计算表达式
所以显示时这两者会有区别
5.8 block.cpp
#include <iostream>
int main()
{
using namespace std;
cout << "The Amazing Accounto will sum and average ";
cout << "five numbers for you.\n";
cout << "Please enter five values:\n";
double number;
double sum = 0.0;
for (int i = 1; i <= 5; i++)
{ // block starts here
cout << "Value " << i << ": ";
cin >> number;
sum += number;
} // block ends here
cout << "Five exquisite choices indeed! ";
cout << "They sum to " << sum << endl;
cout << "and average to " << sum / 5 << ".\n";
cout << "The Amazing Accounto bids you adieu!\n";
// cin.get();
// cin.get();
return 0;
}
该函数展示了for花括号的使用方法
花括号内的语句视为一个代码块
5.9 forstr2.cpp
#include <iostream>
#include <string>
int main()
{
using namespace std;
cout << "Enter a word: ";
string word;
cin >> word;
// physically modify string object
char temp;
int i, j;
for (j = 0, i = word.size() - 1; j < i; --i, ++j)
{ // start block
temp = word[i];
word[i] = word[j];
word[j] = temp;
} // end block
cout << word << "\nDone\n";
// cin.get();
// cin.get();
return 0;
}
#include <iostream>
int main()
{
using namespace std;
int quizscores[10] =
{ 20, 20, 20, 20, 20, 19, 20, 18, 20, 20};
cout << "Doing it right:\n";
int i;
for (i = 0; quizscores[i] == 20; i++)
cout << "quiz " << i << " is a 20\n";
// Warning: you may prefer reading about this program
// to actually running it.
cout << "Doing it dangerously wrong:\n";
for (i = 0; quizscores[i] = 20; i++)
cout << "quiz " << i << " is a 20\n";
// cin.get();
return 0;
}
该函数探究了字符串中等于20的字符,并将其找出来,到非20时停止
之后则是指出了比较字符==与赋值字符=的不同,两者不可弄混
赋值符号=会引发错误,使for一直循环
5.11 compstr1.cpp
#include <iostream>
#include <cstring> // prototype for strcmp()
int main()
{
using namespace std;
char word[5] = "?ate";
for (char ch = 'a'; strcmp(word, "mate"); ch++)
{
cout << word << endl;
word[0] = ch;
}
cout << "After loop ends, word is " << word << endl;
// cin.get();
return 0;
}
该代码是C风格的字符串比较
通过不断改变第一个字符,来比较*ate和mate
直到*从a变到m停止,条件符合
5.12 compstr2.cpp
#include <iostream>
#include <string> // string class
int main()
{
using namespace std;
string word = "?ate";
for (char ch = 'a'; word != "mate"; ch++)
{
cout << word << endl;
word[0] = ch;
}
cout << "After loop ends, word is " << word << endl;
// cin.get();
return 0;
}