有没有办法读取 C++ 中连续特定行上的数字?
Posted
技术标签:
【中文标题】有没有办法读取 C++ 中连续特定行上的数字?【英文标题】:Is there a way to read the numbers on consecutive specific lines in C++? 【发布时间】:2020-11-15 10:02:27 【问题描述】:假设我有一个程序将文件作为输入 (数字.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, );
我该怎么做?
【问题讨论】:
【参考方案1】:通过编写代码来做到这一点。
#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++)
是常用的方式,至少在我看来是这样。
【讨论】:
好的。但是项目中推荐的 B(i) 或 B[i] 的数字在 NEXT 行。例如,在文本文件中可能有:``` 4(数字 N)3 6 98 220(我想要的数字在 A)4 6 12 443(我想要的数字在 B)``` 我还没有使用 operator>> 来处理这种事情,但我猜它只是忽略了空格。换行符 ('\n') 也是空格。 如果我们已经指定了通用循环形式,我会选择 ++i。在优化(生产)二进制文件中,它没有任何区别,但没有优化(例如调试构建) i++ 实际上保存了旧的 i 并因此添加了指令。在大多数情况下可能微不足道,但我会说这是一个好习惯。 @Paul 感谢您的提示,但该项目涉及另一个主题。从现在开始,我将使用 ++i 这样做,但我需要有关矢量部分的帮助。尤其是一整段代码,而不仅仅是这里和那里的说明,散布在整个页面中。我需要 5 行连贯的代码。 @AndrewFNAF operator>> 将在需要时移至下一行。以上是关于有没有办法读取 C++ 中连续特定行上的数字?的主要内容,如果未能解决你的问题,请参考以下文章