// if.cpp -- using the if statement
#include <iostream>
#include <fstream>
int main()
{
using namespace std;
//6.1if
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";
//6.2逻辑表达式
//6.3字符函数库cctype
cin.get(ch); // get first character
while (ch != '@') // test for sentinel
{
if (isalpha(ch)) // is it an alphabetic character?
cout << "is char";
else if (isspace(ch)) // is it a whitespace character?
cout << "is space";
else if (isdigit(ch)) // is it a digit?
cout << "is num";
else if (ispunct(ch)) // is it punctuation?
cout << "is .";
else
cout << "is others";
cin.get(ch); // get next character
}
//6.4 ?:运算符
// c = a if a > b, else c = b
//6.5 switch
enum { red, orange, yellow, green, blue, violet, indigo };
int 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;
}
}
//6.6break continue
char line[60];
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++;
}
//6.7 read num 的循环
const int Max = 5;
double fish[6];
cout << "fish #1: ";
int i = 0;
while (i < Max && cin >> fish[i]) {//转化为bool输入成功为true
if (++i < Max)
cout << "fish #" << i + 1 << ": ";
}
//6.8简单文件in/out
ofstream outFile;
outFile.open("carinfo.txt"); // associate with a file
outFile << "Year: " << endl;
outFile.close(); // done with file
ifstream inFile;
inFile.open("carinfo.txt");
if (!inFile.is_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";
// cin.get();
// cin.get();
return 0;
}
chapter6 分支语句
最新推荐文章于 2024-08-12 20:59:25 发布