Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you tell iostreams which characters to treat as whitespace?

So that you could do something like this, for instance:

std::string a("01:22:42.18");
std::stringstream ss(a);
int h, m, s, f;
ss >> h >> m >> s >> f;

Which normally requires the string to be formatted "01 22 42 18". Can you modify the current locale directly to do this?

like image 928
henle Avatar asked Oct 31 '09 20:10

henle


People also ask

Does CIN read whitespace?

You can use cin but the cin object will skip any leading white space (spaces, tabs, line breaks), then start reading when it comes to the first non-whitespace character and then stop reading when it comes to the next white space. In other words, it only reads in one word at a time.

How do you check if a character is a space in C++?

C++ isspace() The isspace() function in C++ checks if the given character is a whitespace character or not.

Does Ifstream ignore whitespace?

The stream extractors behave the same and skip whitespace. If you want to read every byte, you can use the unformatted input functions, like stream.

How do you read white space in C++?

Now, how to read string with spaces in C++? We can use a function getline(), that enable to read string until enter (return key) not found.


2 Answers

I don't think you can change the default delimiter without creating a new locale, but that seems hackish. What you can use do is use getline with a third parameter specifying the delimiter character or you could read the delimiters and not do anything with them (e.g. ss >> h >> d >> m >> d >> s >> d >> f).

You could also write your own parsing class that handles splitting strings for you. Or better yet, use boost::split from Boost's String Algorithms Library.

like image 192
Firas Assaad Avatar answered Oct 20 '22 00:10

Firas Assaad


You can do this by creating a locale with a ctype facet classifying : as whitespace.

Jerry Coffin explains how you can specify whitespace characters in this answer to another question.

like image 4
James McNellis Avatar answered Oct 19 '22 23:10

James McNellis