close

AddTheNumber

//寫一個程式,讀入一個文字檔,將檔案中所出現的數字相加,將答案輸出。
//Example:
//Input: Asdf j213k as kfjas 932kk s8aklsd Asd klfj 823kjds 23ksad f9ksdaf asdfj89as
//Output: 213+932+8+823+23+9+89=2007

#include< iostream >
#include< fstream >
using namespace std;

void InputFromFile();
void OutputToFile();
int getNumber( char [] );

void main()
{
    OutputToFile();
    InputFromFile();
}

void OutputToFile()
{
    ofstream output( "test.txt" , ios::out );
    char input[ 100 ];
    
    if( !output )
    {
        cerr << "Can't save the file !! " << endl;
        exit( 1 );
    }

    cout << "Please input some characters or numbers: ";
    cin.getline( input , 100 );
    output << input;

    output.close();    
}

void InputFromFile()
{
    ifstream input( "test.txt" , ios::in );
    char str[ 20 ];    
    int counter = 1 , sum = 0;
    
    if( !input )
    {
        cerr << "Can't open the file ! " << endl;
        exit( 1 );
    }
    
    while( input >> str )
    {
        cout << "(" << counter << "): " << str << " → " << getNumber( str );
        sum += getNumber( str );
        cout << endl;
        counter++;
    }
    
    cout << endl;
    cout << "The addtion of number in the characters is: " << sum << endl;
    input.close();
}

int getNumber( char getStr[ 20 ] )
{
    char temp[ 10 ];
    int tempIndex = 0 , strIndex = 0 , result = 0;
    bool flag = false;   //判別有無連續
    int length = strlen( getStr );

    while( length > 0 )
    {
        length--;
        if( isdigit( getStr[ strIndex ] ) ) //如果是數字的話
        {
            if( length == 0 )
            {
                temp[ tempIndex ] = getStr[ strIndex ];
                result = atoi( temp );
            }

            if( flag == false ) //表示第一次讀到數字
            {
                flag = true;
                temp[ tempIndex ] = getStr[ strIndex ];
                tempIndex++;
                strIndex++;
            }
            else
            {
                temp[ tempIndex ] = getStr[ strIndex ];
                tempIndex++;
                strIndex++;
            }
        }
        else
        {
            if( flag == false )
                strIndex++;
            else                 //表示要輸出前面讀到的數字
            {
                flag = false;
                result = atoi( temp );
                tempIndex = 0;
                strIndex++;
            }    
        }
    }

    return result;
}

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 mokiss 的頭像
    mokiss

    筆記○心情

    mokiss 發表在 痞客邦 留言(0) 人氣()