最好的是制作一个函数,逐行读取一个文件,并将每行元素放入一个数组(如果您只是打印只是打印它不存储在数组中)。我使用c函数而不是C++流因为对于大数据它们是速度更快。功能应该使用龟etc用于系统fgetc_unlocked正常工作的大数据。如果当它比的fscanf快,那么你应该更换到龟etc
-5 -6 2 -1 4
1 2 3 4
假设输入像并存储在input.txt中。只需在您的目录中输入input.txt并在相同目录中运行以下代码即可。您可以稍后再进行更改如何使用数字
#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;
}
你是什么意思的“分裂为数字”?你的意思是将它们转换为字符串? – CroCo