c++忽略特定的字符

C++ ignore specific character while cin

本文关键字:字符 c++      更新时间:2023-10-16

我的输入如下:

4 5i 6 7i

不查找并替换为字符串,

我想将这些单独的值存储在double

但是忽略了'i'

a = 4, b = 5, c = 6, d = 7

下面是我正在处理的丑陋代码

我迷路了,请帮帮我

谢谢!

    char c, real[1024], img[1024];
    int i = 0;
    bool flag = false,
    flag2 = false;
    while( c = input.get() )
    {
        if( input.peek() == ' '){
            i = 0;
            flag2 = true;
        }
        if( !flag2 ){
            real[ i++ ] = c;
        }else{
            img[ i++ ] = c;
        }

        if( flag )
        {
            break;
        }
        while( input.peek() == 'i' )
        {
            if( input.peek() == 'i' )
            {
                flag = true;
                i = 0;
                flag2 = true;
            }if( input.peek() == ' ' )
            {
                i = 0;
                flag2 = true;
            }
            input.ignore(1, 'i');
        }

    }
    if( flag ){
        obj.doubleValueA = 0.0  ;
        obj.doubleValueB = atof( real );
        return input;
    }else{
        obj.doubleValueA = atof( real );
        obj.doubleValueB = atof( img );
    }
    return input; // enables  cin >> a >> b >> c
#include<iostream>
#include<vector>
#include<sstream>
#include<ctype>
#include<string>
using namespace std;
int parseNumber( string number )
{
    unsigned i = 0;
    // Find the position where the character starts
    while ( i < number.size() && isdigit( number[i] )
    {
        i++;
    }
    number = number.substr( 0, i );
    // Retrieve the number from the string using stringstream
    stringstream ss( number );
    int result;
    ss >> result;
    // Return the result
    return result;
}
int main()
{
    string input;
    getline( cin, input );
    stringstream ss( input );
    string number;
    vector<int> complexNumbers;
    while ( ss >> number )
    {
        complexNumbers.push_back( parseNumber( number ) );
    }
    for ( unsigned i = 0; i < complexNumbers.size(); i++ )
    {
        cout << complexNumbers[i] << " ";
    }
}