用c++编写的程序,只读取字符串变量的数值.但不起作用
program in c++ that only reads numeric values of a string variable. but not working
我试图用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;
}
}
}
相关文章:
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- 如果用户输入无效,如何使用字符串变量-C++重复输入命令
- 从字符串变量中逐字符读取单词
- 对函数 PlaySound 使用字符串变量
- C++中的字符串变量
- 字符串变量,比如说"字符串str",可以直接复制到数组中吗?
- 我可以用字符串变量而不是它的名字创建容器吗? C++
- 字符串变量的大小
- 为什么我的字符串变量没有打印完整的字符串?
- 字符串变量未更新 c++
- 如何使用 setfill 和 setw 在字符串变量中存储十六进制值
- 在.cpp文件之间传递全局字符串变量?
- 字符串变量顺序
- 为什么可以将整数分配给字符串变量?
- 在qt创建器中调试时如何访问字符串变量的完整值?
- 将字符串变量分配给无符号字符变量
- 在 c++ 中使用字符串变量选择静态类结构,而不带对象
- C++我应该用什么来保存格式化为字符串变量(如sprintf())的文件
- 我有一个字符串变量单词= "APA"
- 将字符串变量从 bash 脚本传递到根宏