文本文件解析C++

Text file parsing C++

本文关键字:C++ 文件 文本      更新时间:2023-10-16

我一直在尝试解析 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 或其他一些无效值。