if语句
if else语句
逻辑运算符:&&、||、!
cctype字符函数库
条件运算符:?:
switch语句
continue和break语句
读取数字的循环
基本文件输入/输出
目录
6.1 if语句
// if.cpp -- using the if statement
#include <iostream>
int main()
{
using std::cin; // using declarations
using std::cout;
char ch;
int spaces = 0;
int total = 0;
cin.get(ch);
while (ch != '.') // quit at end of sentence
{
if (ch == ' ') // check if ch is a space
++spaces;
++total; // done every time
cin.get(ch);
}
cout << spaces << " spaces, " << total;
cout << " characters total in sentence\n";
// cin.get();
// cin.get();
return 0;
}
[wlsh@wlsh-MacbookPro] chapter_6$ ./a.out
The balloonist was an airhead
with lofty goals.
6 spaces, 45 characters total in sentence
6.1.1 ifelse语句
// ifelse.cpp -- using the if else statement
#include <iostream>
int main()
{
char ch;
std::cout << "Type, and I shall repeat.\n";
std::cin.get(ch);
while (ch != '.')
{
if (ch == '\n')
std::cout << ch; // done if newline
else
std::cout << ++ch; // done otherwise
std::cin.get(ch);
}
// try ch + 1 instead of ++ch for interesting effect
std::cout << "\nPlease excuse the slight confusion.\n";
// std::cin.get();
// std::cin.get();
return 0;
}
[wlsh@wlsh-MacbookPro] chapter_6$ g++ ifelse.cpp
[wlsh@wlsh-MacbookPro] chapter_6$ ./a.out
Type, and I shall repeat.
An ineffable joy suffused me as I beheld
Bo!jofggbcmf!kpz!tvggvtfe!nf!bt!J!cfifme
the wonders of modern computing
uif!xpoefst!pg!npefso!dpnqvujoh
^Z
[4]+ Stopped ./a.out
6.1.2 格式化ifelse语句
if()
{
}
//强调语句的块结构
if(){
}
//将语句块与关键字if和else更紧密地结合在一起
6.1.3 ifelse ifelse语句
// ifelseif.cpp -- using if else if else
#include <iostream>
const int Fave = 27;
int main()
{
using namespace std;
int n;
cout << "Enter a number in the range 1-100 to find ";
cout << "my favorite number: ";
do
{
cin >> n;
if (n < Fave)
cout << "Too low -- guess again: ";
else if (n > Fave)
cout << "Too high -- guess again: ";
else
cout << Fave << " is right!\n";
} while (n != Fave);
// cin.get();
// cin.get();
return 0;
}
[wlsh@wlsh-MacbookPro] chapter_6$ g++ ifelseif.cpp
[wlsh@wlsh-MacbookPro] chapter_6$ ./a.out
Enter a number in the range 1-100 to find my favorite number: 50
Too high -- guess again: 25
Too low -- guess again: 37
Too high -- guess again: 21
Too low -- guess again: 27
27 is right!
6.2 逻辑表达式
3种逻辑运算符 OR|| AND&& NOT!
6.2.1 逻辑OR运算符 ||
// or.cpp -- using the logical OR operator
#include <iostream>
int main()
{
using namespace std;
cout << "This program may reformat your hard disk\n"
"and destroy all your data.\n"
"Do you wish to continue? <y/n> ";
char ch;
cin >> ch;
if (ch == 'y' || ch == 'Y') // y or Y
cout << "You were warned!\a\a\n";
else if (ch == 'n' || ch == 'N') // n or N
cout << "A wise choice ... bye\n";
else
cout << "That wasn't a y or n! Apparently you "
"can't follow\ninstructions, so "
"I'll trash your disk anyway.\a\a\a\n";
// cin.get();
// cin.get();
return 0;
}
[wlsh@wlsh-MacbookPro] chapter_6$ g++ or.cpp
[wlsh@wlsh-MacbookPro] chapter_6$ ./a.out
This program may reformat your hard disk
and destroy all your data.
Do you wish to continue? <y/n> n
A wise choice ... bye
6.2.2 逻辑AND运算符 &&
// and.cpp -- using the logical AND operator
#include <iostream>
const int ArSize = 6;
int main()
{
using namespace std;
float naaq[ArSize];
cout << "Enter the NAAQs (New Age Awareness Quotients) "
<< "of\nyour neighbors. Program terminates "
<< "when you make\n" << ArSize << " entries "
<< "or enter a negative value.\n";
int i = 0;
float temp;
cout << "First value: ";
cin >> temp;
while (i < ArSize && temp >= 0) // 2 quitting criteria
{
naaq[i] = temp;
++i;
if (i < ArSize) // room left in the array,
{
cout << "Next value: ";
cin >> temp; // so get next value
}
}
if (i == 0)
cout << "No data--bye\n";
else
{
cout << "Enter your NAAQ: ";
float you;
cin >> you;
int count = 0;
for (int j = 0; j < i; j++)
if (naaq[j] > you)
++count;
cout << count;
cout << " of your neighbors have greater awareness of\n"
<< "the New Age than you do.\n";
}
// cin.get();
// cin.get();
return 0;
}
[wlsh@wlsh-MacbookPro] chapter_6$ g++ and.cpp
[wlsh@wlsh-MacbookPro] chapter_6$ ./a.out
Enter the NAAQs (New Age Awareness Quotients) of
your neighbors. Program terminates when you make
6 entries or enter a negative value.
First value: 28
Next value: 119
Next value: 4
Next value: 80
Next value: 50
Next value: 1
Enter your NAAQ: 23
4 of your neighbors have greater awareness of
the New Age than you do.
6.2.3 用&&来设置取值范围
// more_and.cpp -- using the logical AND operator
#include <iostream>
const char * qualify[4] = // an array of pointers*/
{ // to strings
"10,000-meter race.\n",
"mud tug-of-war.\n",
"masters canoe jousting.\n",
"pie-throwing festival.\n"
};
int main()
{
using namespace std;
int age;
cout << "Enter your age in years: ";
cin >> age;
int index;
if (age > 17 && age < 35)
index = 0;
else if (age >= 35 && age < 50)
index = 1;
else if (age >= 50 && age < 65)
index = 2;
else
index = 3;
cout << "You qualify for the " << qualify[index];
// cin.get();
// cin.get();
return 0;
}
[wlsh@wlsh-MacbookPro] chapter_6$ g++ more_and.cpp
[wlsh@wlsh-MacbookPro] chapter_6$ ./a.out
Enter your age in years: 87
You qualify for the pie-throwing festival.
6.2.4 逻辑NOT运算符 !
// not.cpp -- using the not operator
#include <iostream>
#include <climits>
bool is_int(double);
int main()
{
using namespace std;
double num;
cout << "Yo, dude! Enter an integer value: ";
cin >> num;
while (!is_int(num)) // continue while num is not int-able
{
cout << "Out of range -- please try again: ";
cin >> num;
}
int val = int (num); // type cast
cout << "You've entered the integer " << val << "\nBye\n";
// cin.get();
// cin.get();
return 0;
}
bool is_int(double x)
{
if (x <= INT_MAX && x >= INT_MIN) // use climits values
return true;
else
return false;
}
[wlsh@wlsh-MacbookPro] chapter_6$ g++ not.cpp
[wlsh@wlsh-MacbookPro] chapter_6$ ./a.out
Yo, dude! Enter an integer value: 6234128670
Out of range -- please try again: -90000000000
Out of range -- please try again: 99999
You've entered the integer 99999
Bye
6.2.5 逻辑运算符细节
x > 5 && x < 10
(x > 5) && (x < 10)
!x > 5 //永远是false. !x=0或1
!(x > 5)
6.2.6 其他表示方法
6.3 字符函数库cctype
C++从C语言继承与字符相关的、非常方便的函数软件包,简化函数相关操作
// cctypes.cpp -- using the ctype.h library
#include <iostream>
#include <cctype> // prototypes for character functions
int main()
{
using namespace std;
cout << "Enter text for analysis, and type @"
" to terminate input.\n";
char ch;
int whitespace = 0;
int digits = 0;
int chars = 0;
int punct = 0;
int others = 0;
cin.get(ch); // get first character
while (ch != '@') // test for sentinel
{
if(isalpha(ch)) // is it an alphabetic character?
chars++;
else if(isspace(ch)) // is it a whitespace character?
whitespace++;
else if(isdigit(ch)) // is it a digit?
digits++;
else if(ispunct(ch)) // is it punctuation?
punct++;
else
others++;
cin.get(ch); // get next character
}
cout << chars << " letters, "
<< whitespace << " whitespace, "
<< digits << " digits, "
<< punct << " punctuations, "
<< others << " others.\n";
// cin.get();
// cin.get();
return 0;
}
[wlsh@wlsh-MacbookPro] chapter_6$ g++ cctypes.cpp
[wlsh@wlsh-MacbookPro] chapter_6$ ./a.out
Enter text for analysis, and type @ to terminate input.
AddrenalVision International producer Adrienne Vismonger
andnodasdfasd asdasf
asdfasd
asdfa asf@
86 letters, 9 whitespace, 0 digits, 0 punctuations, 0 others.
6.4 ?:运算符
// condit.cpp -- using the conditional operator
#include <iostream>
int main()
{
using namespace std;
int a, b;
cout << "Enter two integers: ";
cin >> a >> b;
cout << "The larger of " << a << " and " << b;
int c = a > b ? a : b; // c = a if a > b, else c = b
cout << " is " << c << endl;
// cin.get();
// cin.get();
return 0;
}
[wlsh@wlsh-MacbookPro] chapter_6$ g++ condit.cpp
[wlsh@wlsh-MacbookPro] chapter_6$ ./a.out
Enter two integers: 25 28
The larger of 25 and 28 is 28
6.5 switch语句
// switch.cpp -- using the switch statement
#include <iostream>
using namespace std;
void showmenu(); // function prototypes
void report();
void comfort();
int main()
{
showmenu();
int choice;
cin >> choice;
while (choice != 5)
{
switch(choice)
{
case 1 : cout << "\a\n";
break;
case 2 : report();
break;
case 3 : cout << "The boss was in all day.\n";
break;
case 4 : comfort();
break;
default : cout << "That's not a choice.\n";
}
showmenu();
cin >> choice;
}
cout << "Bye!\n";
// cin.get();
// cin.get();
return 0;
}
void showmenu()
{
cout << "Please enter 1, 2, 3, 4, or 5:\n"
"1) alarm 2) report\n"
"3) alibi 4) comfort\n"
"5) quit\n";
}
void report()
{
cout << "It's been an excellent week for business.\n"
"Sales are up 120%. Expenses are down 35%.\n";
}
void comfort()
{
cout << "Your employees think you are the finest CEO\n"
"in the industry. The board of directors think\n"
"you are the finest CEO in the industry.\n";
}
[wlsh@wlsh-MacbookPro] chapter_6$ g++ switch.cpp
[wlsh@wlsh-MacbookPro] chapter_6$ ./a.out
Please enter 1, 2, 3, 4, or 5:
1) alarm 2) report
3) alibi 4) comfort
5) quit
4
Your employees think you are the finest CEO
in the industry. The board of directors think
you are the finest CEO in the industry.
Please enter 1, 2, 3, 4, or 5:
1) alarm 2) report
3) alibi 4) comfort
5) quit
5
Bye!
6.5.1 将枚举量用作标签
// enum.cpp -- using enum
#include <iostream>
// create named constants for 0 - 6
enum {red, orange, yellow, green, blue, violet, indigo};
int main()
{
using namespace std;
cout << "Enter color code (0-6): ";
int code;
cin >> code;
while (code >= red && code <= indigo)
{
switch (code)
{
case red : cout << "Her lips were red.\n"; break;
case orange : cout << "Her hair was orange.\n"; break;
case yellow : cout << "Her shoes were yellow.\n"; break;
case green : cout << "Her nails were green.\n"; break;
case blue : cout << "Her sweatsuit was blue.\n"; break;
case violet : cout << "Her eyes were violet.\n"; break;
case indigo : cout << "Her mood was indigo.\n"; break;
}
cout << "Enter color code (0-6): ";
cin >> code;
}
cout << "Bye\n";
// cin.get();
// cin.get();
return 0;
}
[wlsh@wlsh-MacbookPro] chapter_6$ g++ enum.cpp
[wlsh@wlsh-MacbookPro] chapter_6$ ./a.out
Enter color code (0-6): 3
Her nails were green.
Enter color code (0-6): 5
Her eyes were violet.
Enter color code (0-6): 8
Bye
6.5.2 switch和ifelse
switch语句中的每一个case标签必须是一个单独的值,整数(char),因此无法处理浮点数测试
另外,case标签值还必须是常量,
因此涉及茶取值范围、浮点测试、或两个变量的的比较时,使用if else语句
6.6. break和continue语句
// jump.cpp -- using continue and break
#include <iostream>
const int ArSize = 80;
int main()
{
using namespace std;
char line[ArSize];
int spaces = 0;
cout << "Enter a line of text:\n";
cin.get(line, ArSize);
cout << "Complete line:\n" << line << endl;
cout << "Line through first period:\n";
for (int i = 0; line[i] != '\0'; i++)
{
cout << line[i]; // display character
if (line[i] == '.') // quit if it's a period
break;
if (line[i] != ' ') // skip rest of loop
continue;
spaces++;
}
cout << "\n" << spaces << " spaces\n";
cout << "Done.\n";
// cin.get();
// cin.get();
return 0;
}
[wlsh@wlsh-MacbookPro] chapter_6$ g++ jump.cpp
[wlsh@wlsh-MacbookPro] chapter_6$ ./a.out
Enter a line of text:
Let's do lunch today. You can pay!
Complete line:
Let's do lunch today. You can pay!
Line through first period:
Let's do lunch today.
3 spaces
Done.
6.7 读取数字的循环
// cinfish.cpp -- non-numeric input terminates loop
#include <iostream>
const int Max = 5;
int main()
{
using namespace std;
// get data
double fish[Max];
cout << "Please enter the weights of your fish.\n";
cout << "You may enter up to " << Max
<< " fish <q to terminate>.\n";
cout << "fish #1: ";
int i = 0;
while (i < Max && cin >> fish[i]) {
if (++i < Max)
cout << "fish #" << i+1 << ": ";
}
// calculate average
double total = 0.0;
for (int j = 0; j < i; j++)
total += fish[j];
// report results
if (i == 0)
cout << "No fish\n";
else
cout << total / i << " = average weight of "
<< i << " fish\n";
cout << "Done.\n";
// code to keep VC execution window open if q is entered
// if (!cin) // input terminated by non-numeric response
// {
// cin.clear(); // reset input
// cin.get(); // read q
// }
// cin.get(); // read end of line after last input
// cin.get(); // wait for user to press <Enter>
return 0;
}
Please enter the weights of your fish.
You may enter up to 5 fish <q to terminate>.
fish #1: 30
fish #2: 35
fish #3: 25
fish #4: 40
fish #5: q
32.5 = average weight of 4 fish
Done.
Program ended with exit code: 0
// cingolf.cpp -- non-numeric input skipped
#include <iostream>
const int Max = 5;
int main()
{
using namespace std;
// get data
int golf[Max];
cout << "Please enter your golf scores.\n";
cout << "You must enter " << Max << " rounds.\n";
int i;
for (i = 0; i < Max; i++)
{
cout << "round #" << i+1 << ": ";
while (!(cin >> golf[i])) {
cin.clear(); // reset input
while (cin.get() != '\n')
continue; // get rid of bad input
cout << "Please enter a number: ";
}
}
// calculate average
double total = 0.0;
for (i = 0; i < Max; i++)
total += golf[i];
// report results
cout << total / Max << " = average score "
<< Max << " rounds\n";
// cin.get();
// cin.get();
return 0;
}
[wlsh@wlsh-MacbookPro] chapter_6$ g++ cingolf.cpp
[wlsh@wlsh-MacbookPro] chapter_6$ ./a.out
Please enter your golf scores.
You must enter 5 rounds.
round #1: 88
round #2: 87
round #3: must i?
Please enter a number: 103
round #4: 98
round #5: 89
93 = average score 5 rounds
6.8 简单文件输入/输出
6.8.1 文本I/O和文本文件
6.8.2 写入到文本文件中
// outfile.cpp -- writing to a file
#include <iostream>
#include <fstream> // for file I/O
int main()
{
using namespace std;
char automobile[50];
int year;
double a_price;
double d_price;
ofstream outFile; // create object for output
outFile.open("carinfo.txt"); // associate with a file
cout << "Enter the make and model of automobile: ";
cin.getline(automobile, 50);
cout << "Enter the model year: ";
cin >> year;
cout << "Enter the original asking price: ";
cin >> a_price;
d_price = 0.913 * a_price;
// display information on screen with cout
cout << fixed;
cout.precision(2);
cout.setf(ios_base::showpoint);
cout << "Make and model: " << automobile << endl;
cout << "Year: " << year << endl;
cout << "Was asking $" << a_price << endl;
cout << "Now asking $" << d_price << endl;
// now do exact same things using outFile instead of cout
outFile << fixed;
outFile.precision(2);
outFile.setf(ios_base::showpoint);
outFile << "Make and model: " << automobile << endl;
outFile << "Year: " << year << endl;
outFile << "Was asking $" << a_price << endl;
outFile << "Now asking $" << d_price << endl;
outFile.close(); // done with file
// cin.get();
// cin.get();
return 0;
}
[wlsh@wlsh-MacbookPro] chapter_6$ g++ outfile.cpp
[wlsh@wlsh-MacbookPro] chapter_6$ ./a.out
Enter the make and model of automobile: Flitz Perky
Enter the model year: 2009
Enter the original asking price: 13500
Make and model: Flitz Perky
Year: 2009
Was asking $13500.00
Now asking $12325.50
6.8.3 读取文本文件
// sumafile.cpp -- functions with an array argument
#include <iostream>
#include <fstream> // file I/O support
#include <cstdlib> // support for exit()
const int SIZE = 60;
int main()
{
using namespace std;
char filename[SIZE];
ifstream inFile; // object for handling file input
cout << "Enter name of data file: ";
cin.getline(filename, SIZE);
inFile.open(filename); // associate inFile with a file
if (!inFile.is_open()) // failed to open file
{
cout << "Could not open the file " << filename << endl;
cout << "Program terminating.\n";
// cin.get(); // keep window open
exit(EXIT_FAILURE);
}
double value;
double sum = 0.0;
int count = 0; // number of items read
inFile >> value; // get first value
while (inFile.good()) // while input good and not at EOF
{
++count; // one more item read
sum += value; // calculate running total
inFile >> value; // get next value
}
if (inFile.eof())
cout << "End of file reached.\n";
else if (inFile.fail())
cout << "Input terminated by data mismatch.\n";
else
cout << "Input terminated for unknown reason.\n";
if (count == 0)
cout << "No data processed.\n";
else
{
cout << "Items read: " << count << endl;
cout << "Sum: " << sum << endl;
cout << "Average: " << sum / count << endl;
}
inFile.close(); // finished with the file
// cin.get();
return 0;
}
[wlsh@wlsh-MacbookPro] chapter_6$ g++ sumafile.cpp
[wlsh@wlsh-MacbookPro] chapter_6$ ./a.out
Enter name of data file: carinfo.txt
Input terminated by data mismatch.
No data processed.
6.9 总结