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

How to scan a string without using cin in c++?

本文关键字:cin 扫描 字符串 c++      更新时间:2023-10-16

我想实现以下功能:

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

scanf()仍然有效!!

可以循环使用诸如gets()甚至getch()之类的各种方法来接收字符串。