c++ - 如何在 C++ 中不使用 cin 扫描字符串?

标签 c++ c++11 c++14

我想实现如下功能:

string a;
cin>>a;

但是cin很慢。我想要更快的替代品。一个建议是:

char temp[101]; string a;
scanf("%100s", temp);
a=temp;

但是,要使用它,我必须知道字符串的最大大小,我不知道。

我应该使用什么?

最佳答案

我测试了 fscanfifstream 从文件中读取单词的性能。虽然 fscanf 的性能比 ifstream 好一点,但我认为它不需要改变策略。我假设 scanfcin 的相对性能非常相似。

我的测试平台: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/

相关文章:

c++ - 如何在成员函数内将函数及其参数传递给 std::async

c# - 通过 .exe 文件名杀死一些进程

c++ - 使用 decltype 的类型条件声明

c++ - 隐藏函数的实例化

c++ - 检查二维数组中是否存在任何数字的程序

c++ - 可调用结果类型的推导

c++ - 选择第一个有效表达式

c++ - 输入与输出迭代器 - 命名约定

c++ - auditd 实时事件处理 C/C++

c++ - Boost Spirit X3 和 std::unordered_map