如何将.txt文件中的未知数字整数保存到数组中
how can i save an unknow number integers from a .txt file into an array
我生成了一个data.txt文件,其中包含两列中的大量整数。
如何将这些整数保存到数组中?
如果有帮助的话,你可以在这里找到data.txt。样品:
600000
523887 283708
231749 419866
293707 273512
296065 215334
233447 207124
264381 460210
374915 262848
449017 329022
374111 151212
2933 496970
我试过了,但由于某种原因,它不起作用。。
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream input("data-for-union-find.txt");
int i=0;
float a;
int size=0;
size=i/2;
while (input >> a)
{i++;
}
int *x=new int[size];
int *y=new int[size+1];
for(int j=0;j<(size+1);j++)
{
input>>x[j];
input>>y[j];
cout<<x[j]<<" "<<y[j]<<" "<<j<<endl;
return 0;
}
}
要在数组容量之外添加更多元素,您必须:
- 分配一个新的、更大的阵列
- 将所有元素从旧数组复制到新数组
- 删除旧数组
- 附加新元素
一个更安全的解决方案是使用std::vector
和push_back
方法。
如果您有大量的数据,您可能需要用较大的大小声明std::vector
,以减少重新分配的次数。
我会直接写入一个避免分配的容器:
#include <deque>
#include <iostream>
#include <sstream>
template <typename Sequence>
inline int xvalue(const Sequence& data, std::size_t index) {
return data[2*index];
}
template <typename Sequence>
inline int yvalue(const Sequence& data, std::size_t index) {
return data[2*index + 1];
}
int main() {
std::istringstream stream(""
"600000n"
"523887 283708n"
"231749 419866n"
"293707 273512n"
"296065 215334n"
"233447 207124n"
"264381 460210n"
"374915 262848n"
"449017 329022n"
"374111 151212n"
"2933 496970n");
// Get rid of the suspicious first value:
int suspicious;
stream >> suspicious;
// Use a sequence, which avoids allocations
std::deque<int> data
// Read x,y:
int x;
int y;
while(stream >> x >> y) {
data.push_back(x);
data.push_back(y);
}
// Display:
for(std::size_t i = 0; i < data.size() / 2; ++i)
std::cout << "x = " << xvalue(data, i) << ", y = " << yvalue(data, i) << 'n';
// If you need contiguous memory
std::vector<int> contiguous(data.begin(), data.end());
}
相关文章:
- 检查输入是否不是整数或数字
- 如何找到大于整数的最小数字
- 在数字之间插入 + 或 - 符号以使其等于整数
- 为什么有时我输入一个整数,程序将第一个输入的数字打印成十进制数?
- 整数区间(或 int 数组)中每个数字的出现次数
- 当我输入字符类型的数字时,为什么我无法获得整数?
- 必须首先打印向量 v1 中最接近整数 x 的数字<int>
- 分隔整数 (C++) 的数字
- 如何优化代码以返回最接近给定整数的数字,但给定列表中不存在?
- C++:从文件中读取字符串和整数,并获得最大数字
- 如何在C ++中替换整数的前两位数字?
- 如何计算整数的十进制数字?
- 如何计算整数链中使用了多少次数字?
- 为什么这个程序接受整数和字母数字输入并打印它们? C++ 中的 std::string 也采用整数值吗?
- R 中的算术在数字上比整数更快。这是怎么回事?
- 我想使用 std::stoi 函数在 cpp 中将字符串转换为整数,因为我想在字符串中找到不同数字的总和(在下级酶中)
- 将大数字(10-12 位数字)存储在无序映射中<字符串,整数>
- 在c++中读取文件时,它如何自动将字符放入字符数组,将数字放入整数变量
- 如何从向量转换为<char>数字整数
- 如何将.txt文件中的未知数字整数保存到数组中