【问题标题】:Why i can't to display my string value after assign number to it?为什么我在分配数字后无法显示我的字符串值?
【发布时间】:2020-10-01 16:14:39
【问题描述】:

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

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。它的大小为 0,因此您根本无法对其进行索引。你可以试试push_back
  • 我修复了它仍然无法正常工作
  • cout 可能是行缓冲的,所以 cout &lt;&lt; number 不会打印任何东西,直到输出行尾(你永远不会这样做),或者缓冲区填满(它可能没有),或程序结束。尝试cout &lt;&lt; number &lt;&lt; flushcout &lt;&lt; number &lt;&lt; endl 以获得更可读的输出。

标签: c++ string display


【解决方案1】:

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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-15
    • 2017-01-17
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-16
    相关资源
    最近更新 更多