2013-07-10 25 views
0

人!我一直在努力解決這個問題一段時間,到目前爲止我還沒有找到任何解決方案。(C++)std :: istringstream從字符串中讀取最多6位數字以加倍

在下面的代碼中,我用一個數字初始化一個字符串。然後,我使用std :: istringstream將測試字符串內容加載到double中。然後我把這兩個變量都考慮進去

#include <string> 
#include <sstream> 
#include <iostream> 

std::istringstream instr; 

void main() 
{ 
    using std::cout; 
    using std::endl; 
    using std::string; 

    string test = "888.4834966"; 
    instr.str(test); 

    double number; 
    instr >> number; 

    cout << "String test:\t" << test << endl; 
    cout << "Double number:\t" << number << endl << endl; 
    system("pause"); 
} 

當我運行.exe文件,它看起來像這樣:

字符串測試:888.4834966
雙號888.483
按任意鍵繼續。 。 。

,該字符串具有更多的數字,它看起來像的std :: istringstream只裝的10。6我怎樣才能加載所有的字符串輸入到雙變量?

+1

嘗試'instr.precision(8)'在'instr.str(test)之前'' –

回答

1

您的輸出的精度可能只是沒有顯示在number所有數據。有關如何格式化輸出精度,請參閱此link

+0

標準輸入方法不使用'precision()'。 – aschepler

5
#include <string> 
#include <sstream> 
#include <iostream> 
#include <iomanip> 

std::istringstream instr; 

int main() 
{ 
    using std::cout; 
    using std::endl; 
    using std::string; 

    string test = "888.4834966"; 
    instr.str(test); 

    double number; 
    instr >> number; 

    cout << "String test:\t" << test << endl; 
    cout << "Double number:\t" << std::setprecision(12) << number << endl << endl; 
    system("pause"); 

    return 0; 
} 

它讀取所有數字,它們只是不是全部顯示。您可以使用std::setprecision(在iomanip中找到)更正此問題。還要注意,void main不是標準的,你應該使用int main(並從中返回0)。

1

你的雙重價值888.4834966但是當你使用:

cout << "Double number:\t" << number << endl << endl; 

它採用雙默認的精度,將其設爲手動使用:

cout << "Double number:\t" << std::setprecision(10) << number << endl << endl;