Functions that return char[]

Oct 26, 2008 at 6:21pm
I have written this code as part of a project. if my variable Name has the value "Amazon", how can i change this function so that the output is say Amazon.BAS if x=1.?

char* read(int x)
{
string s3;

switch (x)
{
case 1: s3=".BAS";break;
case 2: s3=".PAR";break;
case 3: s3=".DAT";break;
case 4: s3=".OBS";break;
case 5: s3=".RCH";break;
default:cout<<"wrong argument in read(arg)\n";
};

//Make string s1 contain value held by variable Name;
string s1;
stringstream out;
out << this->Name;
s1 = out.str();


string aFileS =s1+s3;

//convert filename string to Char
char aFile[100];
memset( aFile, '\0', 100 );//sets all values in char-array Radfile to "\0"
aFileS.copy( aFile, aFileS.size() );
cout<<aFile<<endl;
return aFile;
}
Oct 26, 2008 at 6:31pm
Use the string.append() function (should be pretty self-explanatory)
Oct 26, 2008 at 6:34pm
This is one way to do it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <string>

using namespace std;

string chancename (string oldname);
int main()
{
    string name;
    cout<<"Insert name please:\n";
    cin>>name;
    string newname=chancename(name);
    cout<<newname;
    cin.ignore();
    return 0;
}

string chancename(string oldname)
{
       int x;
       string newname;
       cout<<"Please enter value:\n";
       cin>>x;
       switch (x)
{
case 1: newname=oldname+".BAS";break;
case 2: newname=oldname+".PAR";break;
case 3: newname=oldname+".DAT";break;
case 4: newname=oldname+".OBS";break;
case 5: newname=oldname+".RCH";break;
default:cout<<"wrong argument in read(arg)\n";
}
return newname;
}
Oct 26, 2008 at 6:36pm
And @scipio: Don't give away code for free thx
Oct 26, 2008 at 6:40pm
He said he needed it for a project :). Sorry, i dont want to make peoples homework.
Topic archived. No new replies allowed.