Q BgQuestion:

      
Novice
Karma Points: 25
Respect (100%):
posted by  Bullboy8 on 11/6/2009 6:52:02 PM  |  status: Closed  |  Earned Karma: 25

getString function

Course Textbook Chapter Problem Needs by
Software Design Starting Out with C++: From Control Structures Through Objects (6th) by Gaddis 9 5PC 11/13/2009 at 1:00:00 PM
Question Details:
Write a function named "getString" that has a local char array of 80 elements.  The function should ask the user to enter a sentence, and store the sentence in the array.  Then the function should dynamically allocate a char array just large enough to hold the sentence, plus the null terminator.  It should copy the sentence to the dynamilcally allocated array, and then return a pointer to the array.  Demonstrate the function in a complete program.
Bonus Point Alert! Earn +7 additional karma points for helping this gold member.

AAnswers:

Answer Question Ask for clarification
Oracle
Karma Points: 31,807
posted by rapunzel on 11/6/2009 7:51:20 PM  |  status: Live
Asker's Rating: Lifesaver   
Response Details:
please rate - thanks

#include <iostream>
#include <cstring>
using namespace std;
char *getString();
int len(char *);
void copy(char *,char *);

int main()
{ char *str;
  str=getString();
  cout << "The string you entered is: "<<str<< endl;
  system("pause");
   return 0;
}


char *getString()
{  int n=80,l;
   char *p,s[n];
   cout<<"Enter a string: ";
   cin.getline(s,n);
   l=len(s);
   p=new char[l+1];
   copy(p,s);
   return p;
}

int len(char *s)
{ int i=0;  // To hold the number of characters
   
   while(*s!= '\0')
   {i++;
    s++;    
   }
  return i;
}

void copy(char *s1, char *s2)
{int i=0;
 while (*(s2+i)!='\0')
   {*(s1+i)=*(s2+i);
      i++;
   }
*(s1+i)='\0';
}



Note to all members 1. Please 1 question per post 2. Show respect to your fellow members by rating all answers. 3. When rating remember that the first answer is not necessarily the best answer. 4. When answering questions, explain what you are doing, so that the asker will learn, don't just give a meaningless number. 5. Your answers should be your work. Don't copy from another member, this is Karma abuse and possible disciplinary actions against you. and GOOD LUCK to you all!!
Answer Question Ask for clarificarion

Join Cramster's Community

Cramster.com brings together students, educators and subject enthusiasts in an online study community. With around-the-clock expert help and a community of over 100,000 knowledgeable members, you can find the help you need, whenever you need it. Join for free today » How Cramster is different from tutoring »