Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

c++ - How to provide your own delimiter for cin?

In c, I can use newline delimeter ([^ ]) 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 [^] with scanf function in c.

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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, '');

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, '')){
    // Do something with the line
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...