为什么在为其分配编号后无法显示我的字符串值?



我想从我的字符串中获取所有数字,然后将它们推送到矢量,但在此之前,我想显示我的"字符串数字"的值以检查效果,问题是我看不到它。

string napis = "ada87dasu3da1";
string number = "";
int counter = 0;
for(int i = 0; i < napis.size(); i++){
if(isdigit(napis[i]) == true){
number[counter] = (char)napis[i];
counter++;
}else if(isdigit(napis[i]) == false && isdigit(napis[i-1]) == true)
cout << number;       // <- there is a problem
counter = 0;
}

number[i] = ...不会像您期望的那样附加新字符。 它修改给定索引处的现有字符,但没有要修改的字符number因为它始终为空! 您没有做任何事情来增加其size().

您需要改用字符串的push_back()operator+=

number.push_back(napis[i]);
number += napis[i];

此外,当i为 0 时,isdigit(napis[i-1])会超出界限,在您的示例中就是这种情况,因为napis的第一个字符不是数字。 您根本不需要在else中检查isdigit()。 而且你也不需要counter

试试这个:

string napis = "ada87dasu3da1";
string number;
for(size_t i = 0; i < napis.size(); ++i){
if (isdigit(napis[i]){
number += napis[i];
}
else if (!number.empty()) {
cout << number << flush;
number.clear();
}
}
if (!number.empty()){
cout << number << flush;
}

话虽如此,还有其他方法可以编写它,不需要您手动检查和附加每个单独的字符,例如:

const char *digits = "0123456789";
string napis = "ada87dasu3da1";
string number;
string::size_type start = napis.find_first_of(digits);
while (start != string::npos) {
string::size_type end = napis.find_first_not_of(digits, start + 1);
if (end == string::npos) {
number = napis.substr(start);
start = napis.size();
}
else {
number = napis.substr(start, end - start);
start = end + 1;
}
cout << number << flush;
start = napis.find_first_of(digits, start);
}

最新更新