Problem 1: Removing all occurrences of a character
代码:
#include <iostream>
using namespace std;
string CensorString1(string text, string remove);
void CensorString2(string &text, string remove);
int main()
{
string text="hauzcxbdsbhrjdhyhghzyyx";
string remove="zxy";
cout <<CensorString1(text,remove)<< endl;
CensorString2(text,remove);
cout <<text<< endl;
}
string CensorString1(string text, string remove)
{
string result="";
for(int i=0; i<text.length(); i++)
{
bool remain=true;
for(int j=0; j<remove.length(); j++)
{
if(text[i]==remove[j])
{
remain=false;
break;
}
}
if(remain)
{
result+=text[i];
}
}
return result;
}
void CensorString2(string &text, string remove)
{
for(int j=0; j<remove.length(); j++)
{
int pos=0;
while( (pos=text.find(remove[j])) != string::npos)
{
text.erase(pos,1);
}
}
}
结果:
Problem 2: Files and Structs
代码:
#include <iostream>
#include<fstream>
using namespace std;
struct statsT {
int low;
int high;
double average;
};
statsT CalculateStatistics(string filename);
int main()
{
statsT chengji;
string filename="zxy.txt" ;
chengji=CalculateStatistics(filename);
cout<<"average is "<<chengji.average <<endl;
}
statsT CalculateStatistics(string filename) {
statsT stats;
stats.low = 101;
stats.high = -1;
int total = 0;
int count = 0;
ifstream in;
in.open(filename.c_str());
//if (in.fail()) Error("Couldn't read '" + filename + "'");
while(true)
{
int num;
in >> num;
// Check that we read successfully
if (in.fail()) break;
// Update or data if we need to
if (num < stats.low) stats.low = num;
if (num > stats.high) stats.high = num;
cout<<num<<endl;
total += num;
count++;
}
stats.average = double(total)/count;
in.close();
return stats;
}
结果: