Changing the Delimiter For Cin (C++)

How to provide your own delimiter for cin?

istream.getline lets you specify a deliminator to use instead of the default '\n':

cin.getline (char* s, streamsize n, char delim );

or the safer and easier way is to use std::getline. With this method you don't have to worry about allocating a buffer large enough to fit your text.

string s;
getline(cin, s, '\t');

EDIT:

Just as a side note since it sounds like you are just learning c++ the proper way to read multiple deliminated lines is:

string s;
while(getline(cin, s, '\t')){
// Do something with the line
}

Can c++ input separator be changed from space to dot?

The obvious possibility would be something like:

unsigned o1, o2, o3, o4;

char dot1, dot2, dot3;

infile >> o1 >> dot1 >> o2 >> dot2 >> o3 >> dot3 >> o4;

assert(dot1=='.' && dot2=='.' && dot3=='.');
assert(o1 < 256 && o2 < 256 && o3 < 256 && o4 < 256);

If you really don't want to explicitly read the . characters, you can create a ctype facet that classifies . as whitespace, then create a locale using that facet, and imbue the stream with that locale.

If you need to write a lot of code that ignores . in the input, this might be worthwhile. I've posted such a facet in another answer. Here you'd use that, but read ints (or unsigned, etc.) instead of strings.

Can you specify what ISN'T a delimiter in std::getline?

You can't. The default delimiter is \n:

while (std::getline (std::cin, str) // '\n' is implicit

For other delimiters, pass them:

while (std::getline (std::cin, str, ' ') // splits at a single whitespace

However, the delimiter is of type char, thus you can only use one "split-character", but not what not to match.

If your input already happens to be inside a container like std::string, you can use find_first_not_of or find_last_not_of.


In your other question, are you sure you have considered all answers? One uses istream::operator>>(std::istream&, <string>), which will match a sequence of non-whitespace characters.

cin.get() skips when i use getline() with delimiter

The new line character, that was entered by the user after the $, will remain in the input stream as it will not have been consumed by getline(): this is the character that get() reads.

Just use getline, using new line as delimiter (the default).



Related Topics



Leave a reply



Submit