Question

I have string like this 6.28:12.56:-1:1, 4 double values separated by : and I need to get each double constant and each insert into different variable. What is the easiest way to do this? Thanks.

Était-ce utile?

La solution

You would usually use strtok for this (strtok_r if you use threads or may have otherwise overlapping parsing sequences).

Autres conseils

From http://www.dotnetperls.com/split:

String.Split() separates strings. Often strings have delimiter characters in their data. Delimiters include "\r\n" newline sequences and the comma and tab characters. Split handles splitting upon string and character delimiters.

string s = "6.28:12.56:-1:1";
    //
    // Split string on ':'.
    // ...
    //
    string[] words = s.Split(':');

    for(int i=0;i < words.length;i++)
{
    string word1=words[0];
        string word2=words[1];
        string word3=words[2];
        string word4=words[3];
}

For ANSI C

use sscanf

char st[] = "6.28:12.56:-1:1";
double word1, word2, word3, word4;

int rc = sscanf(st, "%lf:%lf:%lf:%lf", &word1, &word2, &word3, &word4);

/* Check that rc is 4 for success */

*sscanf function returns the number of items succesfully read

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top