[英]Is there a way to read the numbers on consecutive specific lines in C++?
假设我有一个程序,它接受一个文件 (numbers.in) 作为输入,该文件在第一行包含一个数字 n,在第二行包含用空格分隔的 n 个数字,在第三行包含其他 n 个分隔的数字通过一个空间。
我确实知道 n 是多少,因为我是从第一行读到的。 我不知道如何跳到第二行并只读取该行的数字,然后到第三行等等。
我想将第二行中的数字保存在向量 A 中,顺序与它们在该行中的顺序相同,而在向量 B 中,则保存第三行中的数字,如图所示。 到目前为止我有这个:
#include <stream>
#include <string>
using namespace std;
ifstream fin("numbers.in");
ofstream fout("result.out");
int main()
{ int N;
string line;
fin>>N;
long long A[N];
unsigned long long B[N];
for(int i=0; i<=N-1; i++)
{
while (!fin.eof())
{
A[i]=getline(fin, );
}
}
for(int i=0; i<=N-1; i++)
{
while (!fin.eof())
{
B[i]=getline(fin, );
}
}
我怎么做?
通过编写代码来做到这一点。
#include <fstream>
#include <vector>
std::ifstream fin("numbers.in");
std::ofstream fout("result.out");
int main()
{
int N;
// read the number of numbers
fin>>N;
// allocate vectors for storing numbers
std::vector<long long> A(N);
std::vector<unsigned long long> B(N);
// read N numbers
for(int i=0; i<=N-1; i++)
{
fin>>A[i];
}
// read another N numbers
for(int i=0; i<=N-1; i++)
{
fin>>B[i];
}
}
for(int i=0; i<=N-1; i++)
的循环还不错,但是for(int i=0; i<N; i++)
是常用的方法,至少在我看来是这样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.