用c++编写的程序,只读取字符串变量的数值.但不起作用

program in c++ that only reads numeric values of a string variable. but not working

本文关键字:字符串 变量 不起作用 读取 c++ 程序      更新时间:2023-10-16

我试图用c++创建一个程序,该程序应该只读取字符串变量的数值。但它似乎不起作用。有人能告诉我为什么吗?

#include <iostream>
#include <string>
using namespace std;
int main() {
    string str = "11111111111";
     for(unsigned i = 0; i<=str.length(); i++) {
        if(str.at(i)!='0' || str.at(i)!='1' ||str.at(i)!='2' ||str.at(i)!='3' ||
           str.at(i)!='4' || str.at(i)!='5' ||str.at(i)!='6' ||str.at(i)!='7' ||
           str.at(i)!='8' || str.at(i)!='9' ||
           str.at(i)!='-' ) {
          cout << "Invalid Phone Number!" << endl;
          cout << str.at(i);
        break;
        }
     }
    cout << str;
}

您可以使用regex:

#include <regex>
std::string str = "11111111111";
if (false == std::regex_match(str, std::regex("[-0-9]+")))
{
  std::cout << "Invalid Phone Number!n";
}
for(unsigned i = 0; i<=str.length(); i++)

将比较更改为i < str.length(),并修复逻辑:

for (unsigned i = 0; i < str.length(); i++) 
{
    if (str[i] < '0' || str[i] > '9')
    {
        if (str[i] != '-')
        {
            cout << str[i] << "n";
            cout << "Invalid Phone Number!" << endl;
            break;
        }
    }
}