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

时间:2016-01-09 04:20:37

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

我想实现以下功能:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    >
    <fragment
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:name="com.nock.app.newbase.ui.ShelfFragment"
        android:id="@+id/fragment_container"/>
</LinearLayout>

public class FragmentActivity extends AppCompatActivity {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list_books);
    }

}

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

string a;
cin>>a;

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

我应该使用什么?

2 个答案:

答案 0 :(得分:3)

我在阅读文件中的单词时测试了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

答案 1 :(得分:0)

仍然scanf()有效!!

可以循环使用gets()甚至getch()等各种方法来接收字符串。