我有下面的代碼應該用「*」替換數字,並用「?」替換字母,但由於某些原因,它部分起作用。你能幫我弄清楚是什麼問題?字符串替換問題
#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;
}
'我<= niz.size()'應該是'我
aschepler
我真的用小於,但它仍然取得了相同的結果,所以我想也許它不會遍歷所有的字符。 – BloodDrunk
如果您告訴我們您正在提供什麼輸入,您得到的輸出以及您期望的輸出,它會有所幫助。 –