忽略用户输入C++中的字母

Ignoring letters in user input C++

本文关键字:C++ 用户 输入      更新时间:2023-10-16

我的代码的简化版本:

vector<double> iV;
double i;
cout << "Enter numbers:n";
while(cin >> i) {
    iV.push_back(i);
}
for (auto e : iV) {
    if (!iV.empty())
        cout << e << endl;
}

它现在所做的是从cin中读取double类型的数字,将它们加载到向量中,然后打印出来。但是,用户必须输入一封信才能提交输入我不想要这个我希望忽略用户输入的任何字母。

例如,

输入数字:
56 f 45.6 200.1 6g

应具有输出:
56
45.6
200.1
6

string process( const string& input ) // Removes all characters except <space>, '.' and digits
{
    string ret;
    for ( const auto& c : input )
    {
        if ( c == ' ' || c == '.' || ( c >= '0' && c <= '9' ) )
        {
            ret += c;
        }
    }
    return ret;
}
int main()
{
    string line;
    vector<double> iV;
    double i;
    while ( getline( cin, line ) )
    {
        line = process( line );
        stringstream ss( line );
        while ( ss >> i )
        {
            iV.push_back( i );
        }
    }
    for ( auto e : iV )
    {
        if ( !iV.empty() )
        {
            cout << e << endl;
        }
    }
}