我想要验证哪些MET数据看起来像这样:
char validBuffer[] = {"N51374114W1160437"};
char invalidBuffer[] = {"bad data\n"};
char emptyBuffer[] = {""};
我尝试过一个简单的sscanf,但失败了:
int _tmain(int argc, _TCHAR* argv[])
{
char validBuffer[] = {"N51374114W1160437"};
char invalidBuffer[] = {"bad data\n"};
char emptyBuffer[] = {""};
char ns = ' ';
char ew = ' ';
int northing = -999;
int easting = -999;
int paramsConverted = sscanf_s(validBuffer, "%c%d%c%d", &ns, &northing, &ew, &easting);
printf("Converted \"%s\"; Found %d params [%c,%d,%c,%d]\n", validBuffer, paramsConverted, ns, northing, ew, easting);
paramsConverted = sscanf_s(invalidBuffer, "%c%d%c%d", &ns, &northing, &ew, &easting);
printf("Converted \"%s\"; Found %d params [%c,%d,%c,%d]\n", invalidBuffer, paramsConverted, ns, northing, ew, easting);
paramsConverted = sscanf_s(validBuffer, "%c%d%c%d", &ns, &northing, &ew, &easting);
printf("Converted \"%s\"; Found %d params [%c,%d,%c,%d]\n", emptyBuffer, paramsConverted, ns, northing, ew, easting);
getchar();
return 0;
}
给了我:
Converted "N51374114W1160437"; Found 2 params [N,-999,",-1024]
Converted "bad data
"; Found 1 params [b,-999,",-1024]
Converted ""; Found 2 params [N,-999,",-1024]
如果可能的话,我宁愿不使用任何外部库,那么有没有一种简单的方法可以一次解析一个字符呢?
答案 0 :(得分:3)
答案 1 :(得分:2)
char validBuffer[] = {"N51374114W1160437"};
char invalidBuffer[] = {"bad data\n"};
char emptyBuffer[] = {""};
if(strlen(validBuffer)!=18)
{
//Error not valid buffer
}
char ns = validBuffer[0];
char ew = validBuffer[9];
int N = atoi(&validBuffer[1]);
int W = atoi(&validBuffer[10]);
if(N==0 || W==0)
//Error not valid buffer
不是简单不是最好的,但总比没有好
答案 2 :(得分:2)
您可以使用std::stringstream
和流媒体操作符......
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
bool parse(string & s) {
stringstream ss(s);
char n = 0, w = 0;
int x = 0, y = 0;
ss >> n;
if (! ss.good ()) return false;
ss >> x;
if (! ss.good ()) return false;
ss >> w;
if (! ss.good ()) return false;
ss >> y;
if ( ss.bad ()) return false;
cout << "Parsed {" << n << ", " << x << ", "
<< w << ", " << y << "}" << endl;
return true;
}
int main ()
{
string validBuffer = "N51374114W1160437";
string invalidBuffer = "bad data\n";
string emptyBuffer = "";
if (! parse (validBuffer))
cout << "Unable to parse: '" << validBuffer << "'" << endl;
if (! parse (invalidBuffer))
cout << "Unable to parse: '" << invalidBuffer << "'" << endl;
if (! parse (emptyBuffer))
cout << "Unable to parse: '" << emptyBuffer << "'" << endl;
return 0;
}
我的输出使用上面的内容:
Parsed {N, 51374114, W, 1160437}
Unable to parse: 'bad data
'
Unable to parse: ''
答案 3 :(得分:1)
考虑sscanf()的位特定格式参数:
int paramsConverted = sscanf(validBuffer, "%c%8d%c%7d", &ns, &northing, &ew, &easting);