2017-04-06 67 views
-2

我有下面的代码应该用“*”替换数字,并用“?”替换字母,但由于某些原因,它部分起作用。你能帮我弄清楚是什么问题?字符串替换问题

#include <iostream> 
#include <string> 
#include <cctype> 

using namespace std; 

int main(){ 

    //Declaring Variables 
    int MAX = 10; 
    string niz = ""; 

    do { 
     //Letting user insert a string 
     cout<<"Write a random set of characters (max. "<<MAX<<" signs): "; 
     getline(cin, niz); 

     //Comparing the size of string with allowed maximum 
     if (niz.size() > MAX){ 

      //Print error message 
      cout<<"String too long."<<endl; 
     } 
    } while (niz.size() > MAX); 

    //Iterating through the string, checking for numbers and letters 
    for (int i = 0; i <= niz.size(); i++){ 

     //If the sign is a digit 
     if (isdigit(niz[i])){ 

      //Replace digit with a "*" 
      niz.replace(i, i, "*"); 

      //If the sign is a letter 
     } else if (isalpha(niz[i])){ 

      //Replace vowel with "?" 
      niz.replace(i, i, "?"); 
     } 
    } 

    //Printing new string 
    cout<<"New string, after transformation, is: "<<niz<<", and its length is: "<<niz.length()<<endl; 
} 
+0

'我<= niz.size()'应该是'我 aschepler

+0

我真的用小于,但它仍然取得了相同的结果,所以我想也许它不会遍历所有的字符。 – BloodDrunk

+0

如果您告诉我们您正在提供什么输入,您得到的输出以及您期望的输出,它会有所帮助。 –

回答

1

在线路niz.replace(i, i, "*");第二i应该是一个1。您的代码将用*********(9 *)代替第9个字符。如果子是TAHN的第二个参数越小,replace将复制子,直到尽可能多的字符可能被替换

如果你是刚刚替换字符串使用一个字符:

niz[i]='*'; 

注单引号(')在角色周围。

+0

谢谢,这个作品,不知道我可以直接替换这些字符。 – BloodDrunk

+0

@BloodDrunk不要忘记upvote如果答案适合你 – Ken

+0

我知道,我只是不被允许投票呢。 – BloodDrunk

0

您正在使用5 形式的:

basic_string& replace(size_type pos, size_type count, 
         const CharT* cstr); 

其被替换count(= i这里)字符从位置pos(也= i这里)。
请注意,带双引号的"*"是一个字符串,而不是单个字符。

您需要做的仅仅

niz[i] = '*'; 

单引号。