C++ primer plus(第六版)学习笔记、习题答案(4.2)

还以为博客没有了,就不添到上一篇了


5_8(1)

// 2014/12/11
#include <iostream>
#include <cstring>

using namespace std;
int main()
{
	char test[20] = {0};
	int count = 0;
	char ch;
	int i = 0;

	cout << "Enter words(to stop ,type the word done):";
	do
	{
		i = 0;
		ch = cin.get();
		while (ch != ' ' && ch != '\n')
		{
			test[i++] = ch;
			ch = cin.get();
		}
		test[i] = '\0';
		count ++;
	}while (strcmp(test,"done") != 0);
	
	cout << "you entered a total of " << count -1 << " words.";

	cin.get();
	cin.get();
	cin.get();
	return 0; 
}

note:程序有个小bug,只输入一个空格,或者回车也会当做一个字符来看待。

后来改了一下

5.8(2)

	// 2014/12/10
	#include <iostream>
	#include <cstring>

	using namespace std;
	int main()
	{
		char test[20] = {0};
		int count = 0;
		char ch;
		int i = 0;

		cout << "Enter words(to stop ,type the word done):";
		do
		{
			i = 0;
			ch = cin.get();
			while (ch != ' ' && ch != '\n')
			{
				test[i++] = ch;
				ch = cin.get();
			}

			//avoid enter the blank or enter the first time

			test[i] = '\0';

			if (strcmp(test,"\0") != 0)
			{
				count ++;
			}
			
		}while (strcmp(test,"done") != 0);
	
		cout << "you entered a total of " << count -1 << " words.";

		//cin.get();
		cin.get();
		cin.get();
		return 0; 
	}

5.9

// 2014/12/11
#include<iostream>
#include<string>

using namespace std;

int main()
{
	const string str = "done";
	string test;
	int i = 0;

	cout << "Enter words (to stop, type the word done)";
	do 
	{
		cin >> test;

		if (test != str)
		{
			i++;
		}

		else
			break;

	} while (true);

	cout << "you entered a total of " << i << "words";

	cin.get();
	cin.get();
	return 0;
}



5.10

// 2014/12/11
#include<iostream>
#include<string>

using namespace std;

int main()
{
	int n;

	cout << "Enter number of rows:";
	cin >> n;
	int i,j,k;

	for (i = 1; i <= n; i++)
	{
		
		for (j = 1; j <= n - i; j++)
		{
			cout << ".";
			
		}
		for (k = 1; k <= i; k++)
		{
			cout << "*";
		}
		cout << endl;
	}
	cin.get();
	cin.get();
	cin.get();
	return 0;
}


希望大家指正。


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值