CFD Online Discussion Forums

CFD Online Discussion Forums (https://www.cfd-online.com/Forums/)
-   OpenFOAM Programming & Development (https://www.cfd-online.com/Forums/openfoam-programming-development/)
-   -   How to read a list of integers from a string? (https://www.cfd-online.com/Forums/openfoam-programming-development/239161-how-read-list-integers-string.html)

NotOverUnderated October 23, 2021 10:05

How to read a list of integers from a string?
 
Hello,
I am trying to convert a word (string) to a list as follows:

Code:

List<Foam::label> indices;
const word w = "(0 0 0)";
w >> indices;

This doesn't work. I know I can read from a dictionary using lookup function but I want to know if it is possible to populate a list from a word containing the values using IStream or any other method without using a dictioanry.

Any ideas?

Thank you

olesen October 28, 2021 15:06

Quote:

Originally Posted by NotOverUnderated (Post 814885)
Hello,
I am trying to convert a word (string) to a list as follows:

Code:

List<Foam::label> indices;
const word w = "(0 0 0)";
w >> indices;

This doesn't work. I know I can read from a dictionary using lookup function but I want to know if it is possible to populate a list from a word containing the values using IStream or any other method without using a dictioanry.

Any ideas?

Thank you


Sure, there are a few ways to do that, but FWIW you would want a string not a 'word' for the intermediate anyhow since a "word" generally should not be containing spaces!
Code:

List<label> indices;


// Use a IStringStream
 string str("( 1 2 3 )");
IStringStream is1(str);
is1 >> indices;

// Parse tokenize directly
string str("( 1 2 3 )");
ITstream is2(str);
is2 >> indices;

// If you have read the input into a list of characters, received from a pipe or whatever
List<char> charbuffer = ....;

UIListStream is3(charbuffer);
is3 >> indices.

// Can even use the same thing for your string
string str("( 1 2 3 )");
UIListStream is4(str.data(), str.length());
is4 >> indices.

Still a few more methods on top of that. If you notice that the UIListStream just takes a pointer and num chars, you'll realize that you can also use these to write your own parser etc.

NotOverUnderated October 28, 2021 18:33

Many thanks for providing the answer. I thought that was not possible.

Thank you


All times are GMT -4. The time now is 15:58.