0

I have a string that is written as follows:

^SYSINFO:2,3,0,3,1,,3

You will notice that there is one digit missing in the line, this may not always be the case. I use sscanf to scan the line and extract the last integer.

sscanf(response_c, "^SYSINFO:%*d,%*d,%*d,%*d,%*d,,%d", &networkattach_i);

How can I compensate for the digit that is currently missing, but may be written also?

The following does NOT work:

sscanf(response_c, "^SYSINFO:%*d,%*d,%*d,%*d,%*d,%*d,%d", &networkattach_i);
Cornel Verster
  • 1,664
  • 3
  • 27
  • 55
  • hint: sscanf is not the only way to read and parse data – mvp Jan 29 '14 at 06:56
  • 1
    Is it always the same digit that may be missing? If so, you can try the `sscanf` format expecting the value and if it doesn't match, fall back on a format with `,,`. If any of them might be missing, you'll need to scan them sequentially, and can use %n to track how many characters have been converted so far. You could instead move to a regular expression with optional sub-expressions, or using `std::istringstream`s - probably easiest with `peek()` to see if the next value's present. – Tony Delroy Jan 29 '14 at 06:57
  • @mvp What is the best way to read and parse data then? – Cornel Verster Jan 29 '14 at 07:02
  • @CornelVerster: `std::getline`, regex, parsing it yourself, etc. are a few that come to mind. – legends2k Jan 29 '14 at 07:33
  • Since you're using C functions, you could use `char *last_comma = strrchr(response_c, ',');` and then look for the number after that. If you wish to be sure that the preceding data is in the format you expect, you'll use the `sscanf()` but stop at the last comma but one, and read that into a variable (`%[,]`) simply so you can tell from the return value of `sscanf()` whether it found that last comma. – Jonathan Leffler Jan 29 '14 at 07:33
  • possible duplicate of [How to split a string in C++?](http://stackoverflow.com/questions/236129/how-to-split-a-string-in-c) – AndersK Jan 29 '14 at 07:37

1 Answers1

2

You can try using getline to parse your string. An example would be,

using namespace std;  
string input = "^SYSINFO:2,3,0,3,1,,3";
istringstream ss(input);
string token;

getline(ss, token, ':'); //reads till SYSINFO  
while(getline(ss, token, ',')) {
    cout << token << '\n';
}
Itachi
  • 1,383
  • 11
  • 22