我想实现如下功能:
string a;
cin>>a;
但是cin很慢。我想要更快的替代品。一个建议是:
char temp[101]; string a;
scanf("%100s", temp);
a=temp;
但是,要使用它,我必须知道字符串的最大大小,我不知道。
我应该使用什么?
最佳答案
我测试了 fscanf
和 ifstream
从文件中读取单词的性能。虽然 fscanf
的性能比 ifstream
好一点,但我认为它不需要改变策略。我假设 scanf
和 cin
的相对性能非常相似。
我的测试平台:Linux,g++ 4.8.4。
在其上运行 wc
时的文件内容:
>> wc socc.in
321 1212 7912 socc.in
相对性能:
Time taken: 0.894997 (using ifstream)
Time taken: 0.724011 (using fscanf)
使用的程序:
#include <cstdio>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <ctime>
void test1(std::string const& filename)
{
std::ifstream infile(filename);
if ( !infile )
{
return;
}
// Extract the words from the file using an ifstream.
std::string a;
while ( infile >> a );
}
void test2(std::string const& filename)
{
FILE* infile = fopen(filename.c_str(), "r");
if ( infile == NULL )
{
return;
}
// Extract the words from the file using an ifstream.
// I know that my file does not have any word longer
// than 999 characters.
char word[1000];
while ( fscanf(infile, "%s", word) == 1 );
fclose(infile);
}
void repeat(void (*fun)(std::string const&),
int count,
std::string const& filename)
{
for ( int i = 0; i < count; ++i )
{
fun(filename);
}
}
void timeFunction(void (*fun)(std::string const&),
int count,
std::string const& filename)
{
clock_t start = std::clock();
repeat(fun, count, filename);
clock_t end = std::clock();
double secs = 1.0*(end-start)/CLOCKS_PER_SEC;
std::cout << "Time taken: " << secs << std::endl;
}
int main(int argc, char** argv)
{
int count = std::atoi(argv[1]);
char* filename = argv[2];
timeFunction(test1, count, filename);
timeFunction(test2, count, filename);
}
程序执行和输出:
>> ./socc 10000 socc.in
Time taken: 0.894997
Time taken: 0.724011
关于c++ - 如何在 C++ 中不使用 cin 扫描字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34689625/