How to provide your own measuring instrument for cin?

In c, I can use the new delimiter ([^ \ n]) with scanf. With which I can save the string. Similarly for cin, I can use getline.

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

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

How to achieve similar functionality with cin object in cpp.

Thank you for your time.

+4
source share
1 answer

istream.getline allows you to specify a separator to use instead of the standard '\n' :

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

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

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

EDIT:

As a side note, since it seems like you're just learning C ++, the correct way to read multiple separator lines is:

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

All Articles