2015-06-03 52 views
1

我一直試圖使用getline來識別我的字符串輸入中的空格。字符不是空格,而是字符之間插入數字。當我通常使用cin時,函數可以正常工作,但不會看到空格。爲什麼數字和特殊字符插入空格?

如何更改以下內容以確保實際空間?

這裏是我的代碼函數getline(字符串快報不再移動):

#include "stdafx.h" 
using namespace std; 
#include <iostream> 
#include <string> 

void encrypt(std::string &iostr, int key) 
{ 
    key %= 26; 
    int ch; 

    for (auto &it : iostr) 
    { 
     ch = tolower(it) + key; 
     if (ch > 'z') 
      ch -= 26; 
     it = ch; 
    } 
} 

int main() 
{ 
    string source; 
    int key = 1; 
    cout << "Paste cyphertext and press enter to shift 1 right: "; 

    getline(cin, source); 
    encrypt(source, key); 


    cout << source << ""; 


    system("pause"); 
    return 0; 
} 

回答

0

之所以你encrypt插入特殊字符是循環不注重空間,通過key碼點轉移他們就像正常字符一樣。

添加一個檢查,看看如果字符是一個小寫字母即可解決問題:

for (auto &it : iostr) 
{ 
    ch = tolower(it); 
    if (!islower(ch)) { 
     continue; 
    } 
    ch += key; 
    if (ch > 'z') { 
     ch -= 26; 
    } 
    it = ch; 
} 
+0

爲什麼不'如果(isspace爲(CH)' – NathanOliver

+0

@NathanOliver此舉有助其他字符,如數字和特殊字符但是,OP的移算法是不適合?這些角色 – dasblinkenlight

+0

完美地工作,我會記住這個檢查,非常感謝dasblinkenlight – bert0nius

0

你被包括空格鍵轉移的所有字符。如果您希望他們留下來,您需要排除班次中的空格。例如,你可以做到以下幾點:

void encrypt(std::string &iostr, int key) 
{ 
    key %= 26; 
    int ch; 

    for (auto &it : iostr) 
    { 
     if (it != ' ') //if not space character then shift 
     { 
     ch = tolower(it) + key; 
     if (ch > 'z') 
      ch -= 26; 
     it = ch; 
     } 
    } 
}