我有下面的代码应该用“*”替换数字,并用“?”替换字母,但由于某些原因,它部分起作用。你能帮我弄清楚是什么问题?字符串替换问题
#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
如果您告诉我们您正在提供什么输入,您得到的输出以及您期望的输出,它会有所帮助。 –