2015-01-07 82 views
0

我正在閱讀一個文本文件,並通過解析(逐行)來提取它的信息片段。 這裏是文本文件的例子:區分數字和其他符號[C++]

0 1.1  9  -4 
a #!b  .c.  f/ 
a4 5.2s sa4.4 -2lp 

到目前爲止,我能夠利用拆分空的空間' '作爲分隔符每行。因此,例如,我可以將"1.1"的值保存到字符串變量中。

我想要做什麼(這裏是我卡住的地方)是確定我正在閱讀的信息是否代表一個數字。使用前面的例子,這些字符串不代表號:a #!b .c. f/ a4 5.2s sa4.4 -2lp 另外,這些字符串都表示數字:0 1.1 9 -4

然後我想存儲表示編號爲雙類型的變量(我知道該怎麼做轉換的字符串加倍部分)。

那麼,如何區分數字和其他符號?我正在使用C++。

+1

如何使用正則表達式? –

+0

你是什麼意思? –

+0

在互聯網上查看它。 –

回答

1

你可以這樣做:

// check for integer 

std::string s = "42"; 

int i; 
if((std::istringstream(s) >> i).eof()) 
{ 
    // number is an integer 
    std::cout << "i = " << i << '\n'; 
} 

// check for real 

s = "4.2"; 

double d; 
if((std::istringstream(s) >> d).eof()) 
{ 
    // number is real (floating point) 
    std::cout << "d = " << d << '\n'; 
} 

eof()檢查使數字後面沒有非數字字符。

0

假設的電流(C++ 11)編譯器,來處理這個最簡單的方法是可能做使用std::stod轉換。您可以將size_t的地址傳遞給該地址,以指示無法在轉換中使用的第一個字符的位置加倍。如果整個輸入轉換爲double,它將是字符串的結尾。如果是任何其他值,則至少有部分輸入未轉換。

size_t pos; 
double value = std::stod(input, &pos); 

if (pos == input.length()) 
    // the input was numeric 
else 
    // at least part of the input couldn't be converted. 
相關問題