使用数组从文件打印整数
Printing integers from a file using an array
我刚开始学习 C++,但在编写程序时遇到了一些问题。它应该对外部文件中的数字进行排序。我已经成功地编写了排序算法的代码,但是我在处理外部文件时遇到了问题。我只是在一个单独的程序中测试一些东西,以了解 ifstream 之类的东西是如何工作的。一旦我更好地了解它的工作原理,我应该能够弄清楚如何将它实现到我的程序中。
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
int main() {
using namespace std;
int count;
ifstream InFile;
InFile.open ("unsorted.txt");
InFile >> count;
int numbers[count];
for(int a = 0; a < count; a++)
InFile >> numbers[a];
cout << numbers << endl;
}
目前,它的输出是 0x7ffc246c98e0 我不确定为什么会这样,我只是想打印我的整数文件。谁能帮助解释我做错了什么?非常感谢。
当你这样做时
cout << numbers << endl;
您打印指向数组第一个元素的指针。
你想要
cout << numbers[a] << '\n';
打印当前元素。
此外,如果您的程序只做这些,那么您实际上 不需要 数组。您只需要一个 int
变量:
int value;
for (int a = 0; a < count; ++a)
{
InFile >> value;
cout << value << '\n';
}
这也解决了可变长度数组的问题(因为没有)。
如果您打算使用 count 变量来计算文件大小或其他内容,这就是您的代码出错的地方。您无法像您尝试的那样计算文件的长度。
while( getline ( InFile, line ) )
{
count += line.length();
}
也许吧,这样试试!!!
如果你使用
InFile>>count;
它会尝试存储 InFile 流中的所有字符串以进行计数,这不是预期的。
我刚开始学习 C++,但在编写程序时遇到了一些问题。它应该对外部文件中的数字进行排序。我已经成功地编写了排序算法的代码,但是我在处理外部文件时遇到了问题。我只是在一个单独的程序中测试一些东西,以了解 ifstream 之类的东西是如何工作的。一旦我更好地了解它的工作原理,我应该能够弄清楚如何将它实现到我的程序中。
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
int main() {
using namespace std;
int count;
ifstream InFile;
InFile.open ("unsorted.txt");
InFile >> count;
int numbers[count];
for(int a = 0; a < count; a++)
InFile >> numbers[a];
cout << numbers << endl;
}
目前,它的输出是 0x7ffc246c98e0 我不确定为什么会这样,我只是想打印我的整数文件。谁能帮助解释我做错了什么?非常感谢。
当你这样做时
cout << numbers << endl;
您打印指向数组第一个元素的指针。
你想要
cout << numbers[a] << '\n';
打印当前元素。
此外,如果您的程序只做这些,那么您实际上 不需要 数组。您只需要一个 int
变量:
int value;
for (int a = 0; a < count; ++a)
{
InFile >> value;
cout << value << '\n';
}
这也解决了可变长度数组的问题(因为没有)。
如果您打算使用 count 变量来计算文件大小或其他内容,这就是您的代码出错的地方。您无法像您尝试的那样计算文件的长度。
while( getline ( InFile, line ) )
{
count += line.length();
}
也许吧,这样试试!!! 如果你使用
InFile>>count;
它会尝试存储 InFile 流中的所有字符串以进行计数,这不是预期的。