C++-练习-62

题目:

修改一下程序:用string对象代替字符数组。这样,该程序将不再需要检查输入的字符串是否过长,同时将输入字符串同字符串""进行比较,以判断是否为空行。

#include <iostream>

const int ArSize = 10;

void strcount(const char* str);

int main()

{

using namespace std;

char input[ArSize];

char next;

cout << "Enter a line:\n";

cin.get(input, ArSize);

while (cin)

{

cin.get(next);

while (next != '\n')

cin.get(next);

strcount(input);

cout << "Enter next line(empty line to quit):\n";

cin.get(input, ArSize);

}

cout << "Bye\n";

return 0;

}

void strcount(const char* str)

{

using namespace std;

static int total = 0;

int count = 0;

cout << "\"" << str << "\" contains ";

while (*str++)

count++;

total += count;

cout << count << " characters\n";

cout << total << " characters total\n";

}

源代码:

#include <iostream>
#include <string>
const int ArSize = 10;

void strcount(const std::string str);

int main()
{
	using namespace std;
	string input;

	cout << "Enter a line:\n";
	getline(cin,input);

	while (input != "")
	{
		strcount(input);
		cout << "Enter next line(empty line to quit):\n";
		getline(cin, input);
	}
	cout << "Bye\n";
	return 0;
}

void strcount(const std::string str)
{
	using namespace std;
	static int total = 0;

	cout << "\"" << str << "\" contains ";
	total += str.size();

	cout << str.size() << " characters\n";
	cout << total << " characters total\n";
}

演示效果:


如果朋友你感觉文章的内容对你有帮助,可以点赞关注文章和专栏以及关注我哈,嘿嘿嘿我会定期更新文章的,谢谢朋友你的支持哈 

猜你喜欢

转载自blog.csdn.net/little_startoo/article/details/143279636