读取数字的文本文件,并存储在C++的整数数组中
Read a text file of numbers and store into an array of integers in C++
我需要从文本文件中存储一个整数数组,但我找不到我需要为它做什么。我想我有代码设置的基础,但我认为我需要将元素转换为整数或其他东西?
我的输出是我的列表:
500201018-5152234-1
但是我的"排序"列表最终是-1,以及一系列大的负数。我将其排除在阵列有问题。
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int array1[30];
int counter=0,n=0;
fstream datafile;
void bubbleSort(int list[], int length);
void selectionSort(int list[], int length);
/////////////
datafile.open("data.txt");
if (!datafile.is_open())
{
cout << "Failure to open." << endl;
return 0;
}
while (!datafile.eof()) {
datafile >> array1[counter];
n++;
cout << array1[counter] << endl;
}
datafile.close();
//////////////////////////////
//bubbleSort(array1, n);
//selectionSort(array1, n);
for (int i = 0; i < n; i++)
cout << array1[i] << ", ";
system("pause");
return 0;
}
永远不要使用 eof()
,因为它会导致错误的程序。原因请参阅 https://stackoverflow.com/a/5837670。
while (n < 30 && datafile >> array1[n]) {
cout << array1[n] << endl;
n++;
}
{
int excess;
if (datafile >> excess) {
cerr << "error: data file too largen";
return;
}
}
这样,n
在程序结束时是正确的。
你的代码都很好,除了:
while (!datafile.eof()) {
datafile >> array1[counter];
n++;
cout << array1[counter] << endl;
}
它应该是:
while (!datafile.eof()) {
datafile >> array1[n];
if ( datafile.fail() ) break;
cout << array1[n] << endl;
n++;
}
只需要一个索引变量(n
)来解析/存储到一维数组中。一段时间后n++
的增量语句应始终是最后一个,以便您正在处理当前元素而不是下一个元素。
法典:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int array1[30];
int n=0;
fstream datafile;
void bubbleSort(int list[], int length);
void selectionSort(int list[], int length);
/////////////
datafile.open("data.txt");
if (!datafile.is_open())
{
cout << "Failure to open." << endl;
return 0;
}
while (!datafile.eof()) {
datafile >> array1[n];
if (datafile.fail()) break;
cout << array1[n] << endl;
n++;
}
datafile.close();
for (int i = 0; i < n; i++)
cout << array1[i] << ", ";
system("pause");
return 0;
}
相关文章:
- 如何反转整数参数包
- enum是C++中的宏变量还是整数变量
- 努力将整数转换为链表。不知道我在这里做错了什么
- 整数不会重复超过随机数
- 在C++中手动调整数组大小
- 检查输入是否不是整数或数字
- C++使用整数的压缩数组初始化对象
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 将"打开的CV图像"中的"颜色"转换为整数格式
- 通过套接字[TCP]传输数据 如何在C / C ++中打包多个整数并使用send() recv()传输数据
- 如何只允许用户输入正整数
- 如何在c++中从文本文件中逐行读取整数
- C++:如何循环通过向量中的整数元素
- 我可以信任表示整数的浮点或双精度来保持精度吗
- 序列化,没有库的整数,得到奇怪的结果
- 在一定长度后从数组中打印时缺少整数
- std::当在256字节边界上写入整数时,流的奇怪行为
- 内联程序集printf将整数解释为地址
- 是否基于数组B整数打印数组A中的整数
- 如何在C++中将整数转换为其数字数组