2016-09-09 137 views
-3

我有一段代码,它接受另一个函数(该函数获取用户输入)的输出并用短划线替换所有空格。或者,相反,这就是它应该做的。相反,它取出字符串的第一个单词并忽略其余部分(例如'Hello World' - >'Hello')。这里是片段:字符串问题

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; 

是否有任何理由为什么这不起作用?

编辑:你是什么意思组合C风格的阵列和std::string

EDIT2:我试过使用std :: replace,但同样的事情发生。

EDIT3:我无法让getline()工作。下面是我如何使用它:

getline(cin, *title, "/n"); 

为什么不工作?

FINAL_EDIT:我终于明白了!这里是我的工作:

void info::title(string* title){ 
    cout << "Enter the name of your mod: "; 
    getline(cin, *title); cout << endl;} 
void info::name(string* name, string title){ 
    replace(title.begin(), title.end(), ' ', '-'); 
    *name = title;} 

再次,谢谢,所有!

+2

有很多原因实际上不起作用! –

+1

@ Creep2DJ这个声明char arr [title.size()+ 1];在C++中无效:) –

+6

TL; DR ['std :: replace'](http://en.cppreference.com/w/cpp/algorithm/replace)。 – juanchopanza

回答

3

这里是一个演示程序,显示如何达到你想要的效果。

#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; 
} 

如果输入字符串"Hello World"

那么输出将看起来像

Enter a title: Hello World 
Hello-World 

我使用的标准算法std::replace_copy_if只展示了如何使用lambda表达式。例如,您也可以替换破折号的制表符。

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

否则正如你看到任务可以在不使用中间阵列来完成,你可以使用标准的算法std::replace_copy通过以下方式

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

。此外,这种声明数组

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

的不是C++标准的声明,尽管一些编译器可以有自己的扩展,允许这样的声明..

也有是在你的函数一个错字。我想你指的

*name = arr; 

代替

*name = title; 
+0

这是-1回答这个不好的问题,+2展示在C++ STL的东西和其他微妙的东西我不知道:) –

+0

你怎么在函数定义中使用变量地址而不是指针? – Creep2DJ

+0

@ Creep2DJ - 这不是一个地址。在这种情况下'&'是指'reference'。 – PaulMcKenzie

0

是否有任何理由,这是行不通的?

是的,你创建临时数组,修改它,然后将未修改的原始字符串分配给第一个参数指向的字符串。

你并不需要在所有临时数组和指针传递是不是C++的方式来做到这一点:

std::string info::name(std::string title) 
{ 
    std::replace(title.begin(), title.end(), ' ', '-'); 
    return title; 
} 

,如果你想使用循环(由作业等要求),只是做了上串本身:

std::string info::name(std::string title) 
{ 
    for(size_t i = 0; i < title.length(); ++i) { 
     if(title[i] == ' ') 
      title[i] = '-'; 
    } 
    return title; 
}