PAT 1073. Scientific Notation(科学計数法文字列シミュレーション)


文字列シミュレーション、難しくありません.
まず文字列digitsですべての数字を記録し、有効桁数が変わらないことを確保します.指数サイズを整数expで記録します.
私はその結果を処理する中で小数点を持たない時にエラーが発生しました--exp+1>=digits.size()、すなわちexp+1<=digits.size()の場合、小数点を持たない場合があります.cout.widthのパラメータは(exp+1)であるべきである.
Sample-1.2 E+10は11ビットのはずです...前は10ビットしか出力していなかったので、ずっと気づかなかった.
後でコードを提出して、sampleが全部過ぎたかどうかを見極めなければなりません.
またcoutの出力フォーマットはドキュメントを調べることができます.クリックしてリンクを開くのを参考にしました
コード:
#include <string>
#include <sstream>
#include <iostream>

using namespace std;

inline int string_to_int(const string& str)
{
	int ret;
	stringstream ss;
	ss << str;
	ss >> ret;
	return ret;
}

int main()
{
	string num, digits;
	int exp;

	cin >> num;
	int cut = num.find('E');
	exp = string_to_int( num.substr(cut+1) );
	digits = num[1];
	digits += num.substr(3, cut - 3);

	if (num[0] == '-')
	{
		cout << '-';
	}

	if ( exp < 0 )
	{   // digits  0.  
		if (exp == -1)
		{
			cout << "0." << digits << endl;
		} else
		{
			cout << "0.";
			cout.width(-exp-1);
			cout.fill('0');
			cout << 0;
			cout << digits << endl;		
		}
	} else if (exp < digits.size() - 1) 
	{   // digits      
		cout << digits.substr(0, exp+1);
		cout << ".";
		cout << digits.substr(exp+1);
	} else 
	{   //      
		cout.flags(ios::left);
		cout.width(exp+1); //  +1...
		cout.fill('0');
		cout << digits;
	}

	return 0;
}