程序不能读取文件
Program not reading file in
当我运行它并键入文件名时,我的程序似乎没有在文件中读取。会不会是因为它不知道去哪里找呢?此外,我的函数返回文件中的行数只返回它出现的内存地址。
#include <iostream>
#include <fstream>
#include<string>
using namespace std;
函数返回TXT文件中输入的字符数:
int return_Characters(ifstream& in)
{
int characters = in.gcount();
return characters;
}
函数,该函数应该获取TXT文件中的行数,并以双精度类型返回该数:
double return_lines(ifstream& in)
{
string name;
double lines = 0;
while(getline(in, name) ){
int count = 0;
lines = count++;
}
return lines;
}
主要功能:
int main()
{
string file_name;
ifstream input_file;
cout << "Please enter the name of your file" << endl;
do循环,读入用户输入的file_name字符串,并运行函数以获取用户输入的TXT文件中的字符和行数:
do {
getline(cin, file_name);
cout << "checking" << ' ' << file_name << endl;
input_file.open(file_name);
int count_characters = return_Characters(input_file);
cout << "the number of characters is equal to " << count_characters << 'n';
double count_lines = return_lines(input_file);
cout << "the number of lines in the file is equal to" << return_lines << 'n';
input_file.close();
}while(!file_name.empty());
cout << "there was an error oepning your file. The program will not exit" << endl;
system("Pause");
return 0;
}
这个函数并不像你描述的那样。它返回在最近一次读取操作中读取的字符数(例如,如果执行in.getline()
,则这一行将返回该行的长度)。
int return_Characters (ifstream&在){Int characters = in.gcount();
return characters;
}
要找出文件的大小,您需要查找到末尾,得到位置,然后查找到开始处。虽然这对于某些系统上的文本文件来说是不可靠的,因为newline
在文件中是两个字节,并且在c中只算作"一个字符"。如果您想计算文件中的字符和行数,那么计算每行中的字符数(让您的return_lines
也接受它读取的字符数的参数)。
在return_lines
函数中,将count
声明为循环中的局部变量。这意味着每次迭代它都会被重置为零,导致lines
也一直被设置为零。
另一个问题是istream::gcount
函数只返回从上次输入操作中读取的字符数,并且由于您不进行任何输入,它将始终返回零。
并且没有理由使用double
来表示行数,因为您永远不会在文件中使用,例如12.3行。使用int
.
您还应该检查文件操作是否成功。当您在return_lines
中正确地执行此操作时,您不会检查文件打开是否成功。
相关文章:
- 正在将csv文件读取为双精度矢量
- 将从格式化文本文件读取的文本数据存储到链表
- C++ 读取文件读取文件不正确
- 使用对象文件读取三角形数据网格
- 如何减慢从 BVH 文件读取的 opengl 动画?
- 从文件读取,并写入函数C++中的数组
- 从对象C++中的文件读取内容时出现分段错误
- 从文件读取并通过矢量输出到控制台
- 尝试将字符串从文件读取到无符号字符向量中
- 如何将文本文件读取到二维数组中并以 c++ 打印
- 简化文件读取的函数
- 如何将逗号分隔的文件读取为 2D int 数组?
- 在 c++ 中将数据从文件读取到队列中
- 'std::wstring_convert'尽可能多地转换(从 UTF8 文件读取块)
- C++,从文件读取到结构,然后读取到向量(结构被推入向量太多次,而不仅仅是一次)
- 文件读取C++包括空格键
- 从文件读取时未将值推回矢量
- 从文件 C++ 读取时的无限循环
- 从同一文件读取和写入?
- 从.txt文件读取到C++中的双精度向量