文本文件解析C++
Text file parsing C++
我一直在尝试解析 c++ 中的文本文件以读取文件中包含的数字。每行的整数数和行数未知。当读取所有整数时,他们将保存该整数,后跟一个","和该行的运行总计。然后,这将输出到用户选择的文件。我编写的代码如下:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
int i=0,b = 0,num = 100;
int *s1;
string myfilename, mystring, filename;
cout << "Enter the name of the file to open:" << endl;
cin >> myfilename;
cout << "Enter the name of the output file" << endl;
cin >> filename;
ifstream inFile;
ofstream outFile("C:\Users\Aidan Howie\Documents\University\Second Year\C++\" + filename + ".txt");
inFile.open("C:\Users\Aidan Howie\Documents\University\Second Year\C++\" + myfilename + ".txt");
if (!inFile)
{
cout << "Cannot open file" << endl;
return -1;
}
while (!inFile.eof())
{
s1 = new int[num];
for (i = 0; i < s1; i++)
{
cout << i << "," << (i + b) / s1;
b = i+b;
cout << endl;
}
}
inFile.close();
system("PAUSE");
}
但是收到错误:
error C2446: '<' : no conversion from 'int *' to 'int'
谁能解释如何解决这个问题,以及是否有更简单的方法来读取文件上的未知整数
s1
是指向整数的指针,而i
是整数。所以基本上你正在做的是检查是否6 < 0x55ddab
.
正确的方法是:i < *s1
另外,不要忘记在 while 循环重复之前delete s1
。
另外,我只是要注意一下,您正在做的事情毫无意义,但是,使用i < *s1
将修复您的错误。
s1
是一个ints
数组,这意味着当你使用没有索引的名称s1
时,它是一个指针。因此,您对i < s1
的比较是询问i
是否小于s1
的地址,这不是有效的比较。您的代码行应如下所示:
for (i = 0; i < num; i++)
此外,inFile.eof()
并没有做你认为的那样。获得 E inFile
OF 的唯一方法是用户键入 ctrl+D。您应该让用户输入一些哨兵值来表示输入结束;例如,0 或 -1 或其他一些无效值。
相关文章:
- .cpp和.h文件中的模板专用化声明
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 文本文件中的单词链表
- CMake-按正确顺序将项目与C运行时对象文件链接
- 使用新行和不使用新行读取文件
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 挂起和取消挂起一个文件DLL
- 如何确定我已使用非编码文件到达 EOF?
- 命名空间中具有.h和.cpp文件的类
- 如何使用ndk-build.cmd构建Android.so文件
- 从包含m行的文件中提取n行,必要时(惰性地)重复该文件
- 读取文件并输入到矢量中
- 在C++中查找文件
- c++库的公共头文件中应该包含什么
- 用c++从输入文件中读取另一行
- Cppcheck生成xml转储文件
- 读取文件的最后一行并输入到链接列表时出错
- 无法编译 rtmidi 测试 cmidiin.cpp 文件, 非法指令
- 如何将内容数组写入文本文件?
- C++ Windows 驱动程序MSB3030无法复制该文件,因为它找不到