C ++仅使用char数组逐个字符地从文件char中读取字符[]

时间:2018-11-20 05:08:02

标签: c++ ifstream

我正在为我的c ++类分配作业,并且我已经接近解决我的问题了。在这一点上,我得到的输出几乎是我所期望的,因此我怀疑我可能误解了此问题的核心概念。我现在正在做的工作的一部分是从用户那里获得一个文件名,读入该文件,然后在替换关键字符的同时显示该文件。例如,:!将替换为'\ n'以换行。我只允许使用iostream和fstream,并且所有文本都必须使用char arrays []处理。在当前输出中,我在第三行上有多余的空间,我不明白它是如何到达那里的。因此,我认为我的逻辑可能不对劲,并且想知道是否有更多经验丰富的程序员可以解释我的错误所在。我朝着正确的方向前进吗?

这是我正在练习的文本文件:1.txt

Type, type, type away :!
compile.
Run.
Hip hip hooray! :! No errors today! :!

这是同一文件的预期输出:1.txt

Type, type, type away
compile. Run. Hip hip hooray! 
No errors today!

这是我得到的输出

Type, type, type away
compile. Run. Hip hip hooray! 
 No errors today! <<-------- extra space at the beginning!

我将在下面粘贴我的代码,随时可以对其进行评论。

#include <iostream>
#include <fstream>
using namespace std;
#define MAX 1024 // this is the maximum allowed number of char in a file.
                 // is it a bad idea to define it as a constant?

int main()
{
    char fileName[256];
    char data[MAX];
    int readFile(char fileName[],char data[]);
    void display(char data[], int counter);
    fstream file;

    cout << "File Name: ";
    cin >> fileName;

    int counter = readFile(fileName, data);
    display(data, counter);

    return 0;
}

int readFile(char fileName[], char data[])
{
    ifstream file;
    file.open(fileName);

    int count = 0;
    while(file.get(data[count]) && count < MAX)
    {
        count++;
    }
    file.close();
    return count;
}

void display(char data[], int counter)
{
    char formatText(char data[], int count);
    for(int i = 0; i < counter; i++)
    {
        if(data[i] == '\n') // I added this if statment in because the newline
        {                   // from the file was getting read, AND the :! was
            data[i] = '\0'; // becoming \n, printing out TWO new lines!
        }

    }
    for(int i = 0; i < counter; i++)
    {
        formatText(data, i);

        if(data[i] != ':') // All tokens have a : before, So i dont want to 
            cout << data[i]; // print out the :'s.
    }
}

char formatText(char data[], int count)
{
    if(data[count] == ':')
    {
        switch(data[count + 1]) // these are the three tokens I have been given,
        {                       // but it has to be expandable for more later.
            case '!': data[count + 1] = '\n';
                break;
            case '<': data[count + 1] = '\"';
                break;
            case '>': data[count + 1] = '\"';
                break;
        }
    }

}

很抱歉,如果在另一篇文章中对此进行了回答,我无法找到(或可能理解)我的问题的答案。感谢您的时间和耐心等待。

1 个答案:

答案 0 :(得分:1)

Type, type, type away :!
compile.
Run.
Hip hip hooray! :! No errors. today! :!

好。格式化的第一件事是删除字符数组中的所有换行符'\ n',这样一来

Type, type, type away :!compile.Run.Hip hip hooray! :! No errors today! :!

然后将所有!前面的:'替换为'\ n',但是如果您注意到在这种状态下,所有:!在下一个索引位置都具有非空格字符,请保存一个。

 :! No errors

那是您的错误,因为它随后将您的序列替换为\n No errors

将输入数据更改为

Type, type, type away :!
compile.
Run.
Hip hip hooray! :!No errors today! :!

解决了额外的空间问题。