Creep2DJ Creep2DJ - 2 months ago 5
C++ Question

Issues with strings

I have a snippet of code that takes the output of another function (that function gets user input) and replaces all spaces with dashes. Or, rather, that's what it's supposed to do. Instead, it takes the first word of the string and ignores the rest (e.g. 'Hello World' -> 'Hello'). Here is the snippet:

void info::name(string* name, string title){
char arr[title.size() + 1];
strcpy(arr, title.c_str());
int o = 0;
while(arr[o] != 0){
if(arr[o] == ' '){
arr[o] = '-';
};
o++;
};
*name = arr;


Is there any reason why this wouldn't work?

EDIT: What do you mean by combining C-style arrays and
std::string
?

EDIT2: I tried using std::replace, but the same thing happens.

Answer

Here is a demonstrative program that shows how the effect you want can be achieved.

#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>

struct A
{
    static std::string name( const std::string &title )
    {
        std::string result;
        result.reserve( title.size() );

        std::replace_copy_if( title.begin(), title.end(),
                              std::back_inserter( result ),
                              []( char c ) { return c == ' '; }, '-' );

        return result;                            
    }
};

int main() 
{
    std::string title;
    std::string name;

    std::cout << "Enter a title: ";

    if ( std::getline( std::cin, title ) ) name = A::name( title );

    std::cout << name << std::endl;

    return 0;
}

If to enter string "Hello World"

then the output will look like

Enter a title: Hello World
Hello-World

I used the standard algorithm std::replace_copy_if only to show how to use lambda expressions. For example you could substitute also the tab character for the dash.

std::replace_copy_if( title.begin(), title.end(),
                      std::back_inserter( result ),
                      []( char c ) { return c == ' ' || c == '\t'; }, '-' );

Otherwise you can use standard algorithm std::replace_copy the following way

std::replace_copy( title.begin(), title.end(),
                   std::back_inserter( result ),
                   ' ', '-' );

As you see the task can be done without using an intermediate array. Moreover this declaration of an array

char arr[title.size() + 1];

is not C++ compliant declaration though some compilers can have their own extensions that allow such declarations..

Also there is a typo in your function. I think you mean

*name = arr;

instead of

*name = title;
Comments