Beginner C/C++

Moderators: None (Apply to moderate this forum)
Number of threads: 5430
Number of posts: 16951

This Forum Only
Post New Thread
Single Post View       Linear View       Threaded View      f

Report
simple string question Posted by darthy on 30 Mar 2003 at 7:48 AM
ho do I return a string. I have tried the following


char* getName(){
{
char name[10];
cout << "Enter name : ";
cin >> name;
return name;
}


char name[10] = getName();
Report
Re: simple string question Posted by Federal102 on 31 Mar 2003 at 6:17 AM
: ho do I return a string. I have tried the following
:
:
: char* getName(){
: {
: char name[10];
: cout << "Enter name : ";
: cin >> name;
: return name;
: }
:
:
: char name[10] = getName();
:
string getName()
{
 string name;
 cout << "Enter name: " ;
 cin >> name;
 return name;
}

string name = getName();


Report
Re: simple string question Posted by stober on 8 Apr 2003 at 5:17 AM
: ho do I return a string. I have tried the following
:
:
: char* getName(){
: {
: char name[10];
: cout << "Enter name : ";
: cin >> name;
: return name;
: }
:
:
: char name[10] = getName();
:
getName() can't return a string that way because name is declared on the stack and goes out of scope as soon as getName() returns. Federal suggested the best solution because it uses c++ class string. But you have a couple more options.
 char* getName(){
 {
     static char name[10];
     cout << "Enter name : ";
     cin >> name;
     return name;
 }
 
 
 char *name = getName();


or

 void getName(char *name){
 {
     cout << "Enter name : ";
     cin >> name;
 }
 
int main()
{
  char name[10]; 
  getName(name);









 

Recent Jobs

Official Programmer's Heaven Blogs
Web Hosting | Browser and Social Games | Gadgets

Popular resources on Programmersheaven.com
Assembly | Basic | C | C# | C++ | Delphi | Flash | Java | JavaScript | Pascal | Perl | PHP | Python | Ruby | Visual Basic
© Copyright 2011 Programmersheaven.com - All rights reserved.
Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
Operated by CommunityHeaven, a BootstrapLabs company.