C Prime plus课后练习
- 5-7
5 - 7
#include<iostream>
#include<cstring>
using namespace std;
typedef struct
{
string name;
int year;
}car;
int main()
{
cout << "How many do u wish to catalog?";
int n;
(cin >> n).get();
car *c = new car[n + 1]; 不 + 1 底下数组就会越界
for(int i = 1; i <= n; i++)
{
cout << "Car #" << i<<endl;
cout << "Please enter the make: ";
getline(cin,c[i].name); 输入字符串 getline(cin,str)
cout << "Please enter the year made: ";
(cin >> c[i].year).get(); 数字 和 字符串 混合输入记得加 .get()
}
for(int i = 1; i<=n; i++)
cout << c[i].year << " " << c[i].name << endl;
}
2. 5 - 8
char 的strcmp 的 使用
&& string 的 直接用法
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
char ch[20];
int count;
while(cin >> ch && strcmp(ch,"done"))
count++;
cout << count;
}
或者<string> 运用关系运算符
string str;
while(cin >> str && str != "done")
*/
3. 6 - 2
6 - 2
#include<iostream>
using namespace std;
int main()
{
cout << "Please Enter one of the following choice: "<<endl;
cout << "c) carnivore p) pianist"<<endl;
cout << "t) tree g) game" <<endl;
cout << "Please enter a c , p , t , or g: ";
char ch;
while(cin.get(ch).get() && (ch !='c' && ch != 'p' && ch!='t' && ch != 'g')) 注意这里要打 cin.get(ch).get() 不然cin.get 要读换行符 输出2个again
{
cout << "again!";
}
switch(ch){
case 'c': cout <<"map is a tree"; break;
case 'p': cout <<"map is black hole";break;
case 't': cout <<"map is nothing";break;
case 'g': cout <<"gg";break;
}
}
4. 6 - 6
6 - 6
#include<iostream>
using namespace std;
struct people{
string name;
double money;
int flag; //设置一个flag 来看是否过10000元
};
int main()
{
int num;
(cin >> num).get();
people * c = new people[num];
for(int i = 0; i < num; i++)
{
getline(cin,c[i].name);
(cin >> c[i].money).get();
if(c[i].money > 1000)
{
c[i].flag = 1;
}
else c[i].flag = 0;
}
cout << "Grand patorns: ";
for(int i = 0; i < num; i++)
{
if(c[i].flag == 1)
cout << c[i].name << " ";
}
cout << endl;
cout << "patorns: ";
for(int i = 0; i < num; i++)
{
if(c[i].flag == 0)
cout << c[i].name << " ";
}
return 0;
}
5 6 - 7
#include<iostream>
using namespace std;
char ch[20];
int isalpha(char ch1[])
{
if((ch1[0] > 'a' && ch1[0] < 'z') || (ch1[0] > 'A' && ch1[0] < 'Z'))
return 1;
else
return 0;
}
int main()
{ int a,b,c;
b = c = a = 0;
cout << "Enter words (q to quit): " <<endl;
while(cin >> ch)
{
if(ch[0] == 'q')
break;
if(isalpha(ch))
{
char *p =ch;
if(*p == 'a' || 'e' || 'i'|| 'o' || 'u')
a++;
else
b++;
}
else
c++;
}
cout << a << " words are beginnig with vowels" << endl;
cout << b << " words are beginnig with consonants" << endl;
cout << c << " others";
return 0;
}