ontherocks
ontherocks

Reputation: 1999

Substitute char array with std::string in an input parameter to a function

Following are two legacy routines. I cannot change the routine declarations.

static bool GetString(char * str);        //str is output parameter
static bool IsStringValid(const char * str);    //str is input parameter

With call as follows

char inputString[1000];

GetString(inputString);

IsStringValid(inputString);

Instead of using fixed char array, I want to use std::string as the input. I am not able get the semantics right (string::c_str).

Upvotes: 1

Views: 1668

Answers (4)

Some programmer dude
Some programmer dude

Reputation: 409206

With IsEmpty it should not be a problem:

std::string str = "Some text here";
IsEmpty(str.c_str());

Though it's pretty useless if you have a std::string as then you would normally just call str.empty().


The other function though, that's harder. The reason is that it's argument is not const, and std::string doesn't allow you to modify the string using a pointer.

It can be solved, by writing a wrapper-function which takes a string reference, and have an internal array used for the actual GetString call, and uses that array to initialize the passed string reference.


Wrapper examples:

// Function which "creates" a string from scratch
void GetString(std::string& str)
{
    char tempstr[4096];
    GetString(tempstr);
    str = tempstr;
}

// Function which modifies an existing string
void ModifyString(std::string& str)
{
    const size_t length = str.size() + 1;
    char* tempstr = new char[length];
    std::copy_n(str.c_str(), tempstr, length);

    ModifyString(tempstr);

    str = tempstr;
    delete[] tempstr;
}

Upvotes: 1

hansmaad
hansmaad

Reputation: 18905

std::string has c_str() which you can use for IsEmpty. There ist no function which gives you a non const pointer. Since std::string's allocation is not guaranteed to be contiguous you cannot do something like &s[0] either. The only thing you can do is to use a temporary char buffer as you do in your example.

std::string s;
char inputString[1000];
std::vector<char> v(1000);

GetString(inputString);
GetString(&v[0]);

s = &v[0];
IsEmpty(s.c_str());

Upvotes: 0

Amit Kumar
Amit Kumar

Reputation: 1507

I think you can use the string container of STL ( Standard template Library ) .

  #include <string>
  bool isempty ( int x ) {
    return ( x == 0 ) ? true : false ;     
  }
  // inside main()

  string s ;
  cin >> s ; // or getline ( cin , s) ;
  bool empty = isEmpty (s.length()) ;

Upvotes: 0

Luchian Grigore
Luchian Grigore

Reputation: 258618

You can't use c_str for the first function, because it returns a const char*. You can pass a std::string by reference and assign to it. As for is empty, you can call c_str on your string, but you'd be better of calling the member empty().

Upvotes: 0

Related Questions