implementing a vector with parameters from code

I have code which takes a string (NMEA sentence) and checks if the checksum value (65 in this example) matches the value of the byte-wise XOR reduction of the characters codes of the raw sentence elements between '$' and '*'


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  int main() { 
    std::istringstream in(""$GPGLL,5425.32,N,107.11,W,82319*65");

    std::string sentence;

    std::getline(in, sentence, '*');

    std::string received_checksum;

    // Save the checksum that was at the end of what we received.
    std::getline(in, received_checksum);

    // Re-compute the check-sum:
    char check = std::accumulate(sentence.begin()+1, sentence.end(), 0,
        [](char sum, char ch) { return sum ^ ch; });

    // Print out both the received and computed checksums:
    std::cout << "received checksum: " << received_checksum;
    std::cout << "\ncomputed checksum: " << std::hex << (int)check << "\n";
} 



id now like to implement this as a vector with parameters, which i am struggling with and looking for a bit of help in the right direction

The first component of the pair is a NMEA sentence type (excluding the $). The second component is a vector of sentence fields, excluding the checksum. The elements of the vector should not include the separating commas. E.g. the first component of the pair could be "GPGLL", the first element of the vector could be "5425.32", and the second element of the vector could be "N".

 
using NMEAPair = pair<string, vector<string>>; //from my header file) 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# include <iostream>
# include <sstream>
# include <algorithm>
# include <string>
# include <vector>

using NMEAPair = std::pair<std::string, std::vector<std::string>>;

int main()
{
    std::istringstream in {"$GPGLL,5425.32,N,107.11,W,82319*65"};

    std::string firstWord{}, secondWord{}, thirdWord{}, fourthWord{}, fifthWord{};
    //perhaps you want to use a bit more imaginative variable names!

    std::vector<NMEAPair> myVec{};

    while (in)
    {
       getline(in, firstWord, ',')
        && getline(in, secondWord, ',')
            && getline(in, thirdWord, ',')
                && getline(in, fourthWord, ',')
                    && getline(in, fifthWord, '*');
        //short-circuit evaluation: https://en.wikipedia.org/wiki/Short-circuit_evaluation
        firstWord = firstWord.substr(1);
        //removing the '$'
        if(in)
        //check stream still valid
        {
         myVec.emplace_back(std::make_pair(firstWord, std::vector<std::string>{secondWord, thirdWord, fourthWord, fifthWord}));
        }
    }
    for (const auto& elem : myVec)
    {
        std::cout << elem.first << "\n";
        for (const auto& elemI : elem.second)
        {
            std::cout << elemI << " ";
        }
    }
}

Last edited on
Topic archived. No new replies allowed.