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
619 views
in Technique[技术] by (71.8m points)

stream - C++ cin char read symbol-by-symbol

I need to read symbol-by-symbol. But I don't know how to read until end of input. As exemple test system will cin>>somecharvariable m times. I have to read symbol-by-symbol all characters. Only m times. How I can do it?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

There are several ways to read one character at a time until you have read them all, and none of them is necessarily the best.

Personally, I’d go with the following code:

char c;
while (cin.get(c)) {
    // Process c here.
}

If you only need to read m characters, consider using a for loop:

char c;
for (unsigned int i = 0; i < m && cin.get(c); ++i) {
    // Process c here.
}

This runs the loop as long as two conditions are fulfilled: (1) less than m characters have been read, and (2) there are still characters to read.

However, both solutions have a drawback: they are relatively inefficient. It’s more efficient to read the m characters in one go.

So first allocate a big enough buffer to store m chars and then attempt to read them:

std::vector<char> buffer(m);
cin.read(&m[0], m);
unsigned total_read = cin.gcount();

Notice the last line – this will tell you whether m characters have been actually read.


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

1.4m articles

1.4m replys

5 comments

56.8k users

...