开发者

How to provide your own delimiter for cin?

开发者 https://www.devze.com 2023-04-02 12:18 出处:网络
In c, I can use newline delimeter ([^\\n]) with scanf. Using which I can store the line. Similarly for cin, I can use getline.

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 scan开发者_开发百科f function in c.

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

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


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
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号