zoukankan      html  css  js  c++  java
  • C++primer plus第六版课后编程题答案8.4(补)

    8.4发现忘记发上来了,现在补上。

    8.4

    #include<iostream>
    #include <string>//出问题时,使用的是cstring,但换成string一样出问题
    using namespace std;
    struct stringy{
    	char *str;
    	int ct;
    };
    void set(stringy &beany,const char t[]);
    void show(const stringy &beany,int count=0);
    void show(const char t[],int count=0);
    void main84()
    {
    	stringy beany;
    	char testing[]="Reality isn't what it used to be.";
    	//char testing[]="Reality";//what it used to be.";
    	set(beany,testing);
    	show(beany);
    	show(beany,2);
    	testing[0]='D';
    	testing[1]='u';
    	show(testing);
    	show(testing,3);
    	show("Done!");
    	cout<<beany.str<<endl;
    	cout<<"here is in"<<endl;
    	
    	if(beany.str!=NULL)	//总会引起中断,说是堆损坏
    	{
    		delete []beany.str;
    		cout<<"no null"<<endl;
    	}
    	else 
    		cout<<"str is null";
    
    	system("pause");
    	
    
    
    }
    
    void set(stringy &beany,const char t[])
    {
    	//delete beany.str;
    	int size=strlen(t);//在这里,t已经退化成了一个指针,不能用sizeof获取长度!!!
    	//int size=sizeof(t);//这里出了问题,长度测试错误,当长度超过八个字符是,直接出错!
    	cout<<"size="<<size<<endl;
    	beany.str=new char[size+1];
    	strcpy(beany.str,t);
    	int sizeofStr=strlen(beany.str);
    	cout<<"Sizeofstr="<<sizeofStr<<endl;
    	beany.ct=size;
    
    
    }
    
    void show(const stringy &beany,int count)
    {
    	cout<<"Stringy show"<<endl;
    	if(count!=0)
    	{
    		for(int j=0;j<count;j++)
    		{
    			//cout<<"in stringy here!"<<j<<endl;
    			//cout<<"Stringy show"<<j<<endl;
    			cout<<"str="<<beany.str<<endl;
    		};
    	}
    	else
    		cout<<"str="<<beany.str<<endl;
    	
    }
    void show(const char t[],int count)
    {
    	cout<<"Testing show:"<<endl;
    	if(count==0)
    		cout<<"str="<<t<<endl;
    	else
    		for(int i=0;i<count;i++)
    		{
    			cout<<"Testing show:"<<i<<endl;
    			cout<<"str="<<t<<endl;
    		}
    
    }


  • 相关阅读:
    Vscode:代码片段
    【转载】生产力终极指南:用了两年,如今才算真正会用VS Code
    VScode中无法导入自定义模块的问题——搭建虚拟环境
    【Pandas】1.数据读取
    【Pandas】入门案例
    【Pandas】概述
    【Pandas】环境配置
    leetcode多线程题目
    Spring AOP
    MySQL最佳实践
  • 原文地址:https://www.cnblogs.com/qq84435/p/3664826.html
Copyright © 2011-2022 走看看