Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to provide your own delimiter for cin?

In c, I can use newline delimeter ([^\n]) with scanf. Using which I can store the line. Similarly for cin, I can use getline.

If I have to store a paragraph, I can simulate the functionality using my own special char delimiter like [^#] or [^\t] with scanf function in c.

char a[30];
scanf("%[^\#]",a);
printf("%s",a);

How to achieve the similar functionality with cin object in cpp.

like image 931
Forever Learner Avatar asked Sep 04 '11 05:09

Forever Learner


People also ask

How do I change the delimiter on my Cin?

It is possible to change the inter-word delimiter for cin or any other std::istream , using std::ios_base::imbue to add a custom ctype facet . If you are reading a file in the style of /etc/passwd, the following program will read each : -delimited word separately.

How do I change my Getline delimiter?

Using std::getline() in C++ to split the input using delimiters. We can also use the delim argument to make the getline function split the input in terms of a delimiter character. By default, the delimiter is \n (newline). We can change this to make getline() split the input based on other characters too!

How do I use CIN Getline?

C++ getline() Function ExampleThe first parameter is the cin object while the second is the bio string variable. When you run the code, you'll be prompted to input some text. After you've done that, hit enter and see the output that has all the text from your input instead of just the first character.

Does CIN get read newline?

getline(char *buffer, int N): It reads a stream of characters of length N into the string buffer, It stops when it has read (N – 1) characters or it finds the end of the file or newline character(\n).


1 Answers

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
}
like image 125
GWW Avatar answered Sep 25 '22 01:09

GWW