从字符串中读取/解析多个 INT

Reading/parsing multiple INTs from a String

本文关键字:INT 字符串 读取      更新时间:2023-10-16

我一直在阅读有关将字符串转换为整数,"atoi"和"strol"C标准库函数以及其他一些我似乎无法理解的事情。

我最初要做的是从字符串中获取一系列数字并将它们放入 int 数组中。以下是字符串的片段(单个字符串中有多行):

getldsscan
AngleInDegrees,DistInMM,Intensity,ErrorCodeHEX
0,0,0,8035
1,0,0,8035
2,1228,9,0
3,4560,5,0
...
230,1587,80,0
231,0,0,8035
232,1653,89,0
233,1690,105,0
234,0,0,8035
...
358,0,0,8035
359,0,0,8035
ROTATION_SPEED,4.99

输出来自我的真空机器人"Neato XV-21"。我已经通过COM端口连接获得了上面的输出,并且目前已将其存储在字符串中。(因为机器人可以输出各种不同的东西)。在这个例子中,我从一个字符串 neatoOutput 中读取,该字符串包含机器人在我请求其激光扫描仪更新后的输出。

"getldsscan"是我发送给机器人的命令,当我获得COM输出时,它只是被读回,所以我们跳过它。下一行只是有关输出的每个值的有用信息,可以跳过该值。从那时起,有趣的数据就会输出出来。


我正在尝试获取每行数据中第二个数字的值。该数字是从扫描仪到障碍物的距离。我想要一个整洁的int distanceArray[360],其中包含从机器人报告的所有距离值。机器人将输出360个距离值。

还没有对错误检查或从每行数据中读取其他值大惊小怪,因为一旦我知道如何提取我想要的当前基本数据,我稍后会得到它们。到目前为止,我可以使用以下内容:

int startIndex = 2 + neatoOutput.find("X",0); //Step past end of line character

所以startIndex应该给我数据开始位置的字符索引,但正如你从上面的例子中看到的,每个数字的值的大小范围从单个字符到4个字符。因此,简单地向前一步通过字符串设定的金额是行不通的。

我想做的是这样的...

neatoOutput.find("n",startIndex );

使用更多的代码,我应该能够一次解析一行。但我仍然对如何提取我想要的行中的第二个数字感到困惑。


如果有人对黑客/编码机器人感兴趣,您可以访问:-

  • http://www.neatorobotics.com/programmers-manual/
  • http://xv11hacking.wikispaces.com/


更新:已解决

谢谢大家的帮助,这是我近期将使用的代码。 你会注意到我最终不需要知道我认为我需要使用的 int startIndex 变量。

//This is to check that we got data back
signed int dataValidCheck = neatoOutput.find("AngleInDegrees",0);
if (dataValidCheck == -1)
    return;
istringstream iss(neatoOutput);
int angle, distance, intensity, errorCode;
string line;
//Read each line one by one, check to see if its a line that contains distance data
while (getline(iss,line))
{
    if (line == "getldsscanr")
        continue;
    if (line == "AngleInDegrees,DistInMM,Intensity,ErrorCodeHEXr")
        continue;
    sscanf(line.c_str(),"%d,%d,%d,%d",&angle,&distance,&intensity,&errorCode); //TODO: Add error checking!
    distanceArray[angle] = distance;
}

试试这个(未经测试,所以可能是小错误):

#include <iostream>
#include <sstream>
#include <string>
#include <cstdio>
using namespace std;
int main()
{
    string s("3,2,6,4n2,3,4,5n");
    istringstream iss(s);
    int a, b, c, d;
    string line;
    while (getline(iss,line))
    {
        // Method 1: Using C
        sscanf(line.c_str(),"%d,%d,%d,%d",&a,&b,&c,&d);

        // Method 2: Using C++
        std::stringstream  lineStream(line);
        char  comma;
        lineStream >> a >> comma >> b >> comma >> c >> comma >> d;

        // do whatever
    }
}

您可以自己解析字符串。很简单。

法典:

int ParseResult(const char *in, int *out)
{
    int next;
    const char *p;
    p = in;
    next = 0;
    while (1)
    {
        /* seek for next number */
        for (; !*p && !isdigit(*p); ++p);
        if (!*p)
            break;  /* we're done */
        out[next++] = atoi(p);  /* store the number */
        /* looking for next non-digit char */
        for (; !*p && isdigit(*p); ++p);
    }
    return next;  /* return num numbers we found */
}