编写通常接受一个参数(字符串的地址),并打印该字符串的函数。然而,如果提供了第二个参数(int类型),且该参数不为0,则该函数打印字符串的次数将为该函数被调用的次数(注意,字符串的打印次数不等于第二个参数的值而等于函数被调用的次数)。是的,这是一个非常可笑的函数,但它让您能够使用本章介绍的一些技术。在一个简单的程序中使用该函数,以演示该函数是如何工作的。
代码:
#include <iostream>
using namespace std;const int strLen = 20;void printStr(char *str, int n = 0);int main()
{char str[strLen] = "bocchi the rock";printStr(str);cout << endl;printStr(str);cout << endl;printStr(str, 10);cout << endl;printStr(str, 30);cout << endl;system("pause");return 0;
}void printStr(char *str, int n)
{static int count = 0;count++;while (n >= 0){if (n == 0){cout << str << endl;return;}else{for (int i = 0; i < count; i++){cout << str << endl;}return;}}
}
运行结果:
CandyBar结构包含3个成员。第一个成员存储candy bar的品牌名称;第二个成员存储candy bar的重量(可能有小数);第三个成员存储candy bar的热量(整数)。 请编写一个程序,它使用一个这样的函数,即将CandyBar的引用、char指针、double和int作为参数,并用最后3个值设置相应的结构成员,最后3个参数的默认值分别为“Millennijum Munch "、2.85和350。另外,该程序还包含一个以 CandyBar 的引用为参数,并显示结构内容的函数。请尽可能使用const。
代码:
#include <iostream>
#include <cstring>
#include <string>
using namespace std;const int strLen = 20;typedef struct CandyBar
{char brand[strLen];double weight;int calories;
} CandyBar;void fill_CandyBar(CandyBar &candyBar, const char brand[] = "Millennium Munch", const double weight = 2.85, const int calories = 350);
void display_CandyBar(const CandyBar &candyBar);int main()
{CandyBar c1, c2;fill_CandyBar(c1);display_CandyBar(c1);cout << endl;fill_CandyBar(c2, "Margaret", 4.28, 900);display_CandyBar(c2);system("pause");return 0;
}void fill_CandyBar(CandyBar &candyBar, const char brand[], const double weight, const int calories)
{strcpy_s(candyBar.brand, brand);candyBar.weight = weight;candyBar.calories = calories;
}void display_CandyBar(const CandyBar &candyBar)
{cout << "Brand:" << candyBar.brand << endl;cout << "Weight:" << candyBar.weight << endl;cout << "Calories:" << candyBar.calories << endl;
}
运行结果:
编写一个函数,它接受一个指向string对象的引用作为参数“并将该string对象的内容转换为大写,为此可使用表6.4描述的函数 toupper()。然后编写一个程序,它通过使用一个循环让您能够用不同的输入来测试这个函数,该程序的运行情况如下:
Enter a string (q to quit) : go away
GO AWAY
Next string (q to quit) : good grief!
GOOD GRIEF!
Next string (q to quit): q
Bye.
代码:
#include <iostream>
#include <cstring>
#include <cctype>
using namespace std;#define QUIT "q"void strUpper(string &str);int main()
{string s;cout << "Enter a string (q to quit): ";getline(cin, s);while (s != QUIT){strUpper(s);cout << s << endl;cout << "Next string (q to quit): ";getline(cin, s);}cout << "Bye!n";system("pause");return 0;
}void strUpper(string &str)
{for (int i = 0; i < str.size(); i++){str[i] = toupper(str[i]);}
}
运行结果:
下面是一个程序框架:
#include<iostream>using namespace std;#include<cstring> //for strlen(),strcpy()struct stringy {char * str; //points to a stringint ct; //length of string (not couting '