MENU











Friday, 17 January 2014

oops week 21

Week 21 solutions

21a) Write a C++ program that reads characters from cin into an array 
that you allocate on thefree store. Read individual characters until 
an asterisk (*) is entered. Do not use a std::string.
Program:

#include<iostream>
using namespace std;
int main()
{
 int max = 10;           // no longer const
 char* a= new char[max]; //  allocated on heap
 int n = 0;

 cout<<"Enter the characters of an array\n";   
 while (cin >> a[n]&&a[n]!='*')    //--- Read into the array
 {
  n++;
 }
 cout<<"Contents in the array are:\n";
 for (int i=0; i<n; i++) 
  cout<<a[i]<<"  ";
}

output:


Enter the characters of an array
abcdefg*

Contents in the array are:
a  b  c  d  e  f  g




21b) Write a C++ program to write a function, char* strdup(const char*) that copies a string
into memory it allocates on the free store. Use the dereference operator * instead.

Program:

#include<iostream>
#include<cstring>
#include<cstdlib>
using namespace std;
char* strdup(const char* s)
{
 size_t len = 1+strlen(s);
 char *p = (char*)malloc(len);
 memcpy(p, s, len);
 return p ;
}

int main()
{
 char* n=new char[20];
 char* copy;
 cout<<"enter a string\n";
 cin>>n;
 copy=strdup(n);
        cout<<"Copied string is :  "<<copy<<endl;
 return 0;
}
output: 
 


enter a string
HelloWorld
Copied string is :  HelloWorld




No comments:

Post a Comment