2015-10-19 45 views
1
#include <iostream> 
#include <string> 
#include <cctype> 
using namespace std; 

int main() { 
string passCode; 

passCode = "1 "; 
int i; 

for(i =0; i < passCode.length();i++){ 
if(isspace(passCode.at(i)) == true){ 

passCode.replace(i,1,"_"); 

} 

} 
cout << passCode << endl; 
return 0; 
} 

上面的代码,我的指示是[用2个字符的字符串passCode中的'_'替换任何空格''。如果没有空间,程序不应该打印任何东西。]如何正确替换字符串C++中的字符?

与我的代码目前的方式是,它输出“1”。当我运行条件检查false而不是true时,它会打印“_”。我不明白为什么要这样做,任何人都看到我不知道的问题? 我不允许使用该算法。头。我也只能在main,no函数或导入的头文件/类中工作。

回答

0

如所述here,isspace不返回布尔值。相反,它返回int,其中非零值表示true,零值表示false。你应该写这样的支票:

if (isspace(passCode.at(i)) != 0) 
+0

我明白了,这是它是如何向我解释: 真要是空白 isspace为( ' ')//真 isspace为(' \ n ')//真 isspace为(' X')//假 没有奇怪它不起作用。非常感谢 – Flower

+2

@Flower在if/while和其他条件语句在C/C++中工作的情况下,如果值非为零 - 假定为TRUE,且值等于零 - 则为FALSE。所以,从技术上讲,你甚至可以写下如果这样:if(isspace(passCode.at(i)))。 –

+0

请注意,这将比“替换任何空间”做得更多。 – juanchopanza

4

对于单个字符,它可能是更容易使用std::replace算法:

std::replace(passCode.begin(), passCode.end(), ' ', '_'); 

如果您不能使用算法头就可以推出自己的replace功能。它可以用一个简单的循环来完成:

template<typename Iterator, typename T> 
void replace(Iterator begin, Iterator end, const T& old_val, const T& new_val) 
{ 
    for (; begin != end; ++begin) 
     if (*begin == old_val) *begin = new_val; 
} 
+1

我想'replace_if' +'isspace'可以装配更好地在这里。它也用在OP的代码中。 – Downvoter

+2

@cad指令说'用'_'“替换任何空格',所以使用'isspace'将会做更多的事情。 – juanchopanza

+0

这不起作用,它表示替换不是std :: – Flower

1

我的代码目前事情是这样的,它输出“1”。当我与假,而不是真正的状态检查运行它,它打印“_”

isspace为当它传递一个空间返回一个非零值。这不一定是1. 另一方面,布尔值true通常设置为1.

当我们将isspace的返回值与true进行比较时,当它们不完全相等时会发生什么? 特别是如果true为1,并且isspace只返回一些非零值?

我认为这是发生在这里。 if条件失败,因为这两个是不同的值。所以空间不会被'_'取代。

+0

是的,在我的程序中,它正在评估一些正面价值,感谢您的帮助。 – Flower

1

你的问题是你使用isspace。如果你读它the documentation for isspace说:

返回值
从零(即真)不同的值。如果确实c是一个空白字符。否则为零(即,假)。

但是,您只是检查它是否返回truefalse。您的编译器应该警告您不匹配,因为isspace返回int,并且您正在检查bool

更改为下面的代码应该为你工作:

if(isspace(passCode.at(i)) != 0) { 
    passCode.replace(i,1,"_"); 
} 

我的答案是基于更特别是围绕你的问题,您的评论说你不能使用任何头除了你已经包括了什么。一个更好的解决方案是answered by juanchopanza,你应该尽可能地使用标准库,而不是编写你自己的代码。

1

你也可以用std::string::find控制一个while循环并用std::string::replace替换空格。

std::string test = "this is a test string with spaces "; 
std::size_t pos = 0; 
while ((pos = test.find(' ', pos)) != std::string::npos) 
{ 
    test.replace(pos, 1, "_"); 
    pos++; 
} 
std::cout << test; 

Live Example