有许多方法可以将stdin中的文本读入std::string
。关于std::string
的一点是,它们根据需要增长,这又意味着它们重新分配。内部std::string
有一个指向固定长度缓冲区的指针。当缓冲区已满并且您请求向其添加一个或多个字符时,std::string
对象将创建一个新的,较大的缓冲区而不是旧的缓冲区,并将所有文本移至新缓冲区。
这一切都是说,如果您知道预先要阅读的文本的长度,那么您可以通过避免这些重新分配来提高性能。
#include <iostream>
#include <string>
#include <streambuf>
using namespace std;
// ...
// if you don't know the length of string ahead of time:
string in(istreambuf_iterator<char>(cin), istreambuf_iterator<char>());
// if you do know the length of string:
in.reserve(TEXT_LENGTH);
in.assign(istreambuf_iterator<char>(cin), istreambuf_iterator<char>());
// alternatively (include <algorithm> for this):
copy(istreambuf_iterator<char>(cin), istreambuf_iterator<char>(),
back_inserter(in));
以上所有将复制在标准输入中找到的所有文本,直到文件结束。如果你只想要一个单一的线,使用std::getline()
:
#include <string>
#include <iostream>
// ...
string in;
while(getline(cin, in)) {
// ...
}
如果你想要一个字符,使用std::istream::get()
:
#include <iostream>
// ...
char ch;
while(cin.get(ch)) {
// ...
}
你用printf是不安全的,应该'的printf(“%S “,s.c_str());'以防止缓冲区溢出。 – LiraNuna 2010-04-11 19:57:22
你说得对,我会纠正它。 – 2010-04-11 21:55:20