C ++忽略特定字符而cin

时间:2015-06-03 04:06:46

标签: c++ iostream

我的意见如下:

4 5i 6 7i

而不是查找和替换字符串,

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

但偷看并忽略了我的

所以

双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

1 个答案:

答案 0 :(得分:2)

#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] << " ";
    }
}