前言
本文围绕C++的文本函数和如何用cin的返回值(True/False)作为判断条件分别展开介绍。参考《C++ Primer Plus》,本篇文章代码均已测试通过。
一、新建头文件和修改源文件
同样的步骤,先按模版新建Day03.h
头文件,定义int Day_03(...) {}
函数,后在BasicFunc.h
文件中导入,再在main.cpp
的程序入口函数main()
函数中调用该函数。如下:
二、分支语句和逻辑运算符
废话不多说,直接上代码:
- 计算输入的字符数
void countText(int isCountText)
{
/*计算输入文本中的字符数和空格数*/
cout << "=======Count Text=======" << endl;
cout << "Enter the text you want: \n";
char ch;
int spaces = 0;
int total = 0;
cin.get(ch);
while (ch != '.')
{
if (ch == ' ')
++spaces;
++total;
cin.get(ch);
};
cout << spaces << " spaces, " << total;
cout << " characters total in sentence\n";
}
- 判断字符类型
void charType(int isCharType)
{
/*判断字符类型*/
cout << "=======Char Type=======" << endl;
char ch;
int whitespace = 0, digits = 0, chars = 0, punct = 0, others = 0;
cin.get(ch);
while (ch != '@')
{
if (isalpha(ch))
chars++;
else if (isspace(ch))
whitespace++;
else if (isdigit(ch))
digits++;
else if (ispunct(ch))
punct++;
else
others++;
cin.get(ch);
}
cout << chars << " letters, "
<< whitespace << " whitespaces, "
<< digits << " digits, "
<< punct << " punctations, "
<< others << " others.\n";
}
- 条件运算符代替
if-else
void condit(int isCondit)
{
/*条件运算符替代 if-else*/
cout << "=======Condition code=======" << endl;
const char x[2][20] = { "Jack ", "at your service\n" };
const char* y = "Quillstone";
for (int i = 0; i < 3; i++)
cout << ((i < 2) ? !i ? x[i] : y : x[1]);
}
- 字符变量与int的转换
void chooseColor(int isChooseColor)
{
/*将枚举变量与int变量进行转换*/
cout << "=======Choose Color=======" << endl;
enum {red, orange, yellow, green, blue, violet, indigo};
int code;
cout << "Enter color code (0 - 6): ";
cin >> code;
while (code >= red && code <= indigo)
{
switch (code)
{
case red: cout << "It's red.\n"; break;
case orange: cout << "It's orange.\n"; break;
case yellow: cout << "It's yellow.\n"; break;
case green: cout << "It's green.\n"; break;
case blue: cout << "It's blue.\n"; break;
case violet: cout << "It's violet.\n"; break;
case indigo: cout << "It's indigo.\n"; break;
}
cout << "Enter color code (0 - 6): ";
cin >> code;
};
cout << "【Out】\n";
}
- 利用
cin
返回值作为条件
void countFish(int isCountFish)
{
/*利用cin的返回值作为条件*/
cout << "=======Count Fish=======" << endl;
const int Max = 5;
double fish[Max];
cout << "Please enter the weights of your fish.\n"
<< "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 << ": ";
};
*/
// 添加字符纠正cin输入后:
int i;
for (i = 0; i < Max; i++)
{
cout << "fish #" << i + 1 << ": ";
while (!(cin >> fish[i]))
{
cin.clear();
while (cin.get() != '\n')
continue;
cout << "Please enter a number: ";
}
}
double total = 0.0;
for (int j = 0; j < i; j++)
total += fish[j];
if (i == 0)
cout << "No fish\n";
else
cout << total / i << " = average weight of " << i << "fish\n";
cout << "Done.\n";
}
- 文本函数
void editTxtFile(int isEditTxtFile)
{
/*Cpp的文本函数*/
cout << "=======Edit TxtFile=======" << endl;
char automobile[8];
int year;
double a_price, b_price;
ofstream outFile;
outFile.open("editOutFile.txt");
// 保存屏幕输出的文本字符串及数据
cout << "Enter the make and model of automobile: ";
cin >> automobile;
cout << "Enter the model year: ";
cin >> year;
cout << "Enter the original asking price: ";
cin >> a_price;
b_price = 0.913 * a_price;
// 屏幕上输出信息
cout << fixed; // ios文件定义函数
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 $" << b_price << endl;
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 $" << b_price << endl;
outFile.close();
// 打开已创建的文本文件,计算文件中的数值
const int SIZE = 60;
char filename[SIZE];
ifstream inFile;
cout << "Enter the name of data file: ";
cin >> filename;
inFile.open(filename);
if (!inFile.is_open())
{
cout << "Could not open the file " << filename << endl;
cout << "Program terminating\n";
exit(EXIT_FAILURE);
}
double value;
double sum = 0.0;
int count = 0;
inFile >> value;
// not EOF
while (inFile.good())
{
++count;
sum += value;
inFile >> 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();
}
Day03.h
中的全部代码:
/*Day03:
* 1.学习C++基础语法,包括分支语句和逻辑运算符
* 2.记忆vs c++软件快捷键
Larissa857
2/7/2025
*/
#pragma once
#include "source.h"
using namespace std;
void showmenu_03(void); // 展示功能菜单
void countText(int isCountText); // 计算输入文本中的空格数和英文字符数
void charType(int isCharType); // 判断字符类型
void condit(int isCondit); // 条件运算符的简洁表达
void chooseColor(int isChooseColor); // 将枚举变量与int变量进行比较
void countFish(int isCountFish); // 计算捕获的鱼数量,关键在利用cin的返回值作为条件
void editTxtFile(int isEditTxtFile); // Cpp的文本函数
int Day_03()
{
int sign;
cout << "Hello! Welcome to the C++ world——Day03";
cout << endl;
cout << "What can I help you?" << endl;
showmenu_03();
cin >> sign;
switch (sign)
{
case 0: cout << "【Done】" << endl; break;
case 1: countText(sign); break;
case 2: charType(sign); break;
case 3: condit(sign); break;
case 4: chooseColor(sign); break;
case 5: countFish(sign); break;
case 6: editTxtFile(sign); break;
case 7: cout << "Nothing to deal with :)" << endl; break;
}
return 3;
}
void showmenu_03(void)
{
/*展示功能函数菜单*/
cout << "Please enter 1, 2, 3, 4, 5 or 6:\n"
"1) countText\t\t\t2) charType\n"
"3) condit \t\t4) chooseColor\n"
"5) countFish\t\t\t6) editTxtFile\n"
"7) quit\n";
}
void countText(int isCountText)
{
/*计算输入文本中的字符数和空格数*/
cout << "=======Count Text=======" << endl;
cout << "Enter the text you want: \n";
char ch;
int spaces = 0;
int total = 0;
cin.get(ch);
while (ch != '.')
{
if (ch == ' ')
++spaces;
++total;
cin.get(ch);
};
cout << spaces << " spaces, " << total;
cout << " characters total in sentence\n";
}
void charType(int isCharType)
{
/*判断字符类型*/
cout << "=======Char Type=======" << endl;
char ch;
int whitespace = 0, digits = 0, chars = 0, punct = 0, others = 0;
cin.get(ch);
while (ch != '@')
{
if (isalpha(ch))
chars++;
else if (isspace(ch))
whitespace++;
else if (isdigit(ch))
digits++;
else if (ispunct(ch))
punct++;
else
others++;
cin.get(ch);
}
cout << chars << " letters, "
<< whitespace << " whitespaces, "
<< digits << " digits, "
<< punct << " punctations, "
<< others << " others.\n";
}
void condit(int isCondit)
{
/*条件运算符替代 if-else*/
cout << "=======Condition code=======" << endl;
const char x[2][20] = { "Jack ", "at your service\n" };
const char* y = "Quillstone";
for (int i = 0; i < 3; i++)
cout << ((i < 2) ? !i ? x[i] : y : x[1]);
}
void chooseColor(int isChooseColor)
{
/*将枚举变量与int变量进行转换*/
cout << "=======Choose Color=======" << endl;
enum {red, orange, yellow, green, blue, violet, indigo};
int code;
cout << "Enter color code (0 - 6): ";
cin >> code;
while (code >= red && code <= indigo)
{
switch (code)
{
case red: cout << "It's red.\n"; break;
case orange: cout << "It's orange.\n"; break;
case yellow: cout << "It's yellow.\n"; break;
case green: cout << "It's green.\n"; break;
case blue: cout << "It's blue.\n"; break;
case violet: cout << "It's violet.\n"; break;
case indigo: cout << "It's indigo.\n"; break;
}
cout << "Enter color code (0 - 6): ";
cin >> code;
};
cout << "【Out】\n";
}
void countFish(int isCountFish)
{
/*利用cin的返回值作为条件*/
cout << "=======Count Fish=======" << endl;
const int Max = 5;
double fish[Max];
cout << "Please enter the weights of your fish.\n"
<< "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 << ": ";
};
*/
// 添加字符纠正cin输入后:
int i;
for (i = 0; i < Max; i++)
{
cout << "fish #" << i + 1 << ": ";
while (!(cin >> fish[i]))
{
cin.clear();
while (cin.get() != '\n')
continue;
cout << "Please enter a number: ";
}
}
double total = 0.0;
for (int j = 0; j < i; j++)
total += fish[j];
if (i == 0)
cout << "No fish\n";
else
cout << total / i << " = average weight of " << i << "fish\n";
cout << "Done.\n";
}
void editTxtFile(int isEditTxtFile)
{
/*Cpp的文本函数*/
cout << "=======Edit TxtFile=======" << endl;
char automobile[8];
int year;
double a_price, b_price;
ofstream outFile;
outFile.open("editOutFile.txt");
// 保存屏幕输出的文本字符串及数据
cout << "Enter the make and model of automobile: ";
cin >> automobile;
cout << "Enter the model year: ";
cin >> year;
cout << "Enter the original asking price: ";
cin >> a_price;
b_price = 0.913 * a_price;
// 屏幕上输出信息
cout << fixed; // ios文件定义函数
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 $" << b_price << endl;
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 $" << b_price << endl;
outFile.close();
// 打开已创建的文本文件,计算文件中的数值
const int SIZE = 60;
char filename[SIZE];
ifstream inFile;
cout << "Enter the name of data file: ";
cin >> filename;
inFile.open(filename);
if (!inFile.is_open())
{
cout << "Could not open the file " << filename << endl;
cout << "Program terminating\n";
exit(EXIT_FAILURE);
}
double value;
double sum = 0.0;
int count = 0;
inFile >> value;
// not EOF
while (inFile.good())
{
++count;
sum += value;
inFile >> 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();
}
运行一下: