如何将字符串中的多个浮点数转换为多个浮点数? (sscanf的)

时间:2014-07-11 02:40:55

标签: c++ type-conversion

易于理解:

string=" 2.34 5.21 7.22\n";

我想让字符串的浮点数浮动变量:

float x,y,z;
sscanf(string, " %f %f %f\n",&x,&y,&z);

它应该是这样的,但它不起作用,如何正确转换它?

- 编辑 -

由于这不起作用,让我看看我的其余代码是否有任何问题:

#include <iostream>
#include <stdio.h>
#include <tchar.h>
#include "SerialClass.h"    // Library described above
#include <string>
using namespace std;

bool acabou(char str[]){
    for(int i=0;str[i]!='\0';i++){
        if(str[i]=='\n'){
            return true;
        }
    }
    return false;
}

int main(){
    float x,y,z;
    char buffer[256] = "";
    Serial* SP = new Serial("\\\\.\\COM5");
    if (SP->IsConnected())
        printf("Conectado com sucesso\n");
    while(SP->IsConnected()){
        char incomingData[256] = "";
        int dataLength = 256;
        int readResult = 0;
        readResult = SP->ReadData(incomingData,dataLength);
        if(readResult!=-1){
            strcat(buffer,incomingData);
            if(acabou(incomingData)){
                printf("%s",buffer);
                sscanf(buffer,"%f %f %f\n",&x,&y,&z);
                cout << x << " " << y << " " << z << endl;
                strcpy(buffer,"");
            }
        }else if(acabou(incomingData)){
            printf("%s",buffer);
            sscanf(buffer,"%f %f %f\n",&x,&y,&z);
            cout << x << " " << y << " " << z << endl;
            strcpy(buffer,"");
        }
    }
    return 0;
}

2 个答案:

答案 0 :(得分:1)

坚持使用C ++

std::istringstream iss{string};

float x{}, y{}, z{};

iss >> x >> y >> z;

也就是说,假设string的类型为char const*,您的代码应按原样运行。

答案 1 :(得分:1)

代码从一开始就是正确的, @ user657267 的代码也在运行。

问题出在我的代码中,字符串以,作为变量的十进制到整数的分隔符,我做了一个简单的函数来将,更改为.及其现在正在工作。

感谢您的帮助。