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

来源:互联网 发布:知乎 一二级市场套利 编辑:程序博客网 时间:2024/06/10 06:36

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


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 timetest[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++;}elsebreak;} 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 0
原创粉丝点击