2015-10-19 82 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