2016-01-20 63 views
0

我試圖做一個程序解析GPS值($ GPRMC)。C++字符串加倍

首先成功地解析從全行的字符串。

$GPRMC,062513.000,A,3645.9487,N,12716.8382,E,1.76,295.08,160116,,,A*6E 

之後我做了它,我使用函數stod()爲字符串是雙。

但它崩潰,如果我調試。

代碼在這裏。

#include<iostream> 
#include<string> 


using namespace std; 


//"$GPRMC,062513.000,A,3645.9487,N,12716.8382,E,1.76,295.08,160116,,,A*6E"; 

int main() 
{ 
    string gps="$GPRMC,062516.000,A,3645.9494,N,12716.8365,E,1.82,302.69,160116,,,A*63"; 

    int com_1; 
    int com_2; 
    int com_3; 
    int com_4; 
    int com_5; 
    int com_6; 
    int com_7; 
    int com_8; 
    int com_9; 

    string kind; 
    string time; 
    string state; 
    string latitude; 
    string n_s; 
    string longitude; 
    string e_w; 
    string knot; 
    string degree; 

    double Kind; 
    double Time; 

    double Latitude; 

    double Longitude; 

    double Knot; 
    double Degree; 

    com_1=gps.find(","); 
    com_2=gps.find(",",com_1+1); 
    com_3=gps.find(",",com_2+1); 
    com_4=gps.find(",",com_3+1); 
    com_5=gps.find(",",com_4+1); 
    com_6=gps.find(",",com_5+1); 
    com_7=gps.find(",",com_6+1); 
    com_8=gps.find(",",com_7+1); 
    com_9=gps.find(",",com_8+1); 


    kind=gps.substr(0,com_1); 
    time=gps.substr(com_1+1,com_2-com_1-1); 
    //state=gps.substr(com_2+1,com_3-com_2-1); 
    latitude=gps.substr(com_3+1,com_4-com_3-1); 
    //n_s=gps.substr(com_4+1,com_5-com_4-1); 
    longitude=gps.substr(com_5+1,com_6-com_5-1); 
    //e_w=gps.substr(com_6+1,com_7-com_6-1); 
    knot=gps.substr(com_7+1,com_8-com_7-1); 
    degree=gps.substr(com_8+1,com_9-com_8-1); 


    Kind=stod(kind); 
    Time=stod(time); 
    //State=stod(state); 
    Latitude=stod(latitude); 
    //N_s=stod(n_s); 
    Longitude=stod(longitude); 
    //E_w=stod(e_w); 
    Knot=stod(knot); 
    Degree=stod(degree); 
+1

*但是如果我調試就崩潰了*你能解釋一下嗎? – NathanOliver

+0

您是否嘗試過調試您的代碼?逐行使用一個調試器來查看它實際上是否符合您的期望,並且所有變量都按照您的期望設置? –

+1

看起來您正在嘗試將文本「$ GPRMC」轉換爲整數。我在該字符串中看不到任何小數位數。 –

回答

0
Kind=stod(kind); 

看起來不正確。 kind的值將是"$GPRMC"。您無法從中提取double

PS修復它可能不修復你可能擁有的任何其他問題。

1

在回顧,讓我們考慮如何解析第一個數據。

com_1=gps.find(","); 

上面的代碼找到了第一個逗號的位置,很好。

接下來,提取第一項的子:

kind=gps.substr(0,com_1); 

變量kind應該是 「$ GPRMC」,根據您的輸入。

最後,你這個文本轉換爲雙:因爲有字符串中沒有數字

Kind=stod(kind); 
// In other words, this is equivalent to 
// Kind = stod("$GPRMC"); 

stod功能失效。

順便說一句,不同的變量名稱,如kindKind,被認爲是不良的編碼做法。大多數編碼準則禁止這種情況,並要求變量名稱的區別大於大小寫。