c++字符串中数字的个数

  1. 字符串中的数字个数

输入一行字符,长度不超过 100,请你统计一下其中的数字字符的个数。

输入格式
输入一行字符。注意其中可能包含空格。

输出格式
输出一个整数,表示字数字字符的个数。

输入样例:
I am 18 years old this year.
输出样例:
2
这是我的代码:

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

int main()
{
    int ans = 0;
    string s;
    getline (cin, s);
    for (int i = 0; i < s.size(); i ++ )
        if (s[i] >= '0' and s[i] <= '9')
            ans ++ ;
    cout << ans << endl;
}

我有个疑问,其他的我都懂,但是循环中的s[i]什么意思为什么要带上[i]直接s为什么不行,我试过了,编译错误,有谁能我讲讲其中的c++知识

if (s[i] >= '0' and s[i] <= '9')
改为
if (s[i] >= '0' && s[i] <= '9')
=========
and是python中的用法

s[i]表示字符串中第i个字符
and替换成&&,不是所有编译器都支持alternative tokens(比如msvc就不支持,但gcc, clang支持)
https://en.cppreference.com/w/cpp/language/operator_alternative