从文件中获取字符串并将其拆分
Getting string from file and split that
我正在尝试找到从文件中获取数字的最快方法。可能有负数。我的前夫。输入:
5 3
-5 -6 2 -1 4
1 2 3 4
4 3 2 1
我正在使用:
getline(cin, line);
istringstream linestream(line);
linestream >> var;
结果还可以,但是我的程序在上次测试中有运行时间错误,也许是最小的。100 000个数字。我的问题是,是否有一种比我的解决方案更快地将字符串分为数字的方法?时间是最重要的。
如果输入中只有数字,则可以这样做:
std::vector<int> numbers;
int i;
while(cin >> i) {
numbers.push_back(i);
}
要停止cin
的输入/kbd> z 取决于您的操作系统。
到达文件末尾时,文件的输入将自动停止。
请参阅C 弦乐太慢,如何加快速度?
对于您的运行时错误,您没有发布可编译的代码,而您的错误是在您未发布的内容中。
最好的是制作一个函数,该函数逐行读取文件,并将每个行元素放入数组中(如果您只是在打印只是打印,则不要将其存储在数组中)。我am使用C函数代替C 流,因为对于大数据,它们应使用用于大数据时的FGETC,该功能应比FSCANF快。
-5 -6 2 -1 4
1 2 3 4
假设输入如上所述,并存储在Input.txt中。只需在dir中制作input.txt,然后在同一dir中运行以下代码。您可以稍后进行更改,如何使用数字
#include<iostream>
#include<cstdio>
using namespace std;
#define GC fgetc // replace with fgetc_unlocked if it works in your system(Linux)
//This function takes a line of f and put all integers into A
//and len is number of elements filled
void getNumsFromLine( FILE* f, int *A, int& len){
register char ch=GC(f);
register int n=0;
register bool neg = false;
len=0;
while( ch!='n' ){
while( ch !='-' && (ch>'9' || ch<'0') ) ch=GC(f);
if( ch=='-') {
neg = true;
ch = GC(f);
}
while( ch>='0' && ch<='9' ){
n = (n<<3)+(n<<1)+ch-'0';
ch = GC(f);
}
if(neg) {
n=-n;
neg=false;
}
A[len++]=n;
n=0;
}
}
int main(){
FILE* f=fopen("input.txt", "r");
int A[10][2],len;
for( int i=0; i<2; i++ ){
getNumsFromLine( f, A[i], len );
for( int j=0; j<len; j++ ) cout << A[i][j] <<" ";
cout << endl;
}
fclose(f);
return 0;
}
相关文章:
- 如何拆分文件中.txt字母并使用c ++使用数组进行扑克?
- OpenCV 4.1.2 - 从网络摄像头获取帧并将其拆分
- C++(.cpp文件和.h文件)拆分代码并添加一个函数,提取 - 这很容易吗?
- 将字符串拆分为标记,并将标记拆分为两个单独的数组
- 拆分字符数组并存储为向量
- Boost Asio SerialPort。无法创建并打开串口服务
- 如何将一个单词拆分成字母,并将它们放入一个无序的列表/集合中
- 如何插入十六进制值并发送到串口?
- 如何拆分整数并将所有内容添加到数组中?
- C++17 在逗号上拆分 constexpr 字符串并在编译时有元素的数量?
- Qt读取串行输入,然后将其拆分为单独的变量
- 拆分字符串输入并查找字符是否有效
- 将字符串拆分为单个单词并将它们放置在向量中
- 创建一个程序,该程序将一串数字作为输入,并输出偶数和奇数的总和
- 分解打包的 int 值并将其拆分为两个组件 c++
- 使用 std::regex 拆分一行并丢弃空元素
- 按空格拆分字符串并将列输出到不同的数组中
- Getline() 为第二行并按空格拆分 - C++
- 如何在C++中读取文件并拆分每一行
- 如果有必要,删除边缘并拆分连接的组件(c++, Boost)