如何在c++中不使用cin扫描字符串
How to scan a string without using cin in c++?
我想实现以下功能:
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
scanf()
仍然有效!!
可以循环使用诸如gets()
甚至getch()
之类的各种方法来接收字符串。
相关文章:
- C++中的cin.ignore()函数不适用于整个流
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- Problems with std::cin.fail()
- 检查不带转换的扫描格式
- 由cin中的字符串中未捕获空白引起的分割错误
- 在C++中使用Cin,我如何在1行中输入
- 将 cin 限制为只有一个
- cin >> int 给定一个字符串将 int 赋值为 0
- istream std::cin如何修改自定义istream缓冲区
- C++ 将 CIN 值存储到任何类型的数组中
- 为什么无论你输入什么,这"while(cin.get(str,3))"只运行一次?
- cin 的十进制输入验证?
- Turbo C++ cin() 不能与 gets() 一起使用
- 使用 cin 时接受小数点后的 2 位数字
- 在 std::getline 和 std::cin 期间卡在循环中
- 我无法在Visual Studio代码中使用CIN输入答案,它说输入您的年龄,但它说只读文本编辑器如何解决这个问题?
- 为什么我的两个 cin 语句没有在程序结束时运行?
- C++ cin.ignore() 跳过循环
- 模拟扫描( "%1d" ) 用于C++ (std::cin)
- 如何在c++中不使用cin扫描字符串