读取文件并向后显示

时间:2019-07-02 05:43:50

标签: c++

我需要编写一个程序来从文件中读取所有数据,并通过包括这部分代码来在c ++中向后显示内容。为了读取和显示单个字符,请使用数字(0-9),字母(a-z或A-Z),符号(&^#)或空格

python -m pip install jupyter

所以我需要做的是提示用户输入文件名 一次从一个文件读取文件中的数据,并将其存储在字符串中,然后编写一个函数以向后显示结果字符串的上下文。

2 个答案:

答案 0 :(得分:0)

您可以一次读取一个字符的内容,检查它是字母数字还是符号之一,然后将其附加到字符串中,然后使用std :: reverse对其进行反转。

#include <iostream>
#include <cctype>
#include <fstream>
#include <string>

int main()
{
    std::cout << "Please enter the filename: ";
    std::string filename;
    std::cin >> filename;

    std::string contents;
    std::ifstream file(filename, std::ifstream::in);

    if (file.good())
    {
        char c;
        const std::string symbols = "&^# ";

        while (file >> std::noskipws >> c)
        {
            if (isalnum || symbols.find(c) != std::string::npos)
            {
                contents += c;
            }
        }

        std::reverse(contents.begin(), contents.end());
    }

    std::cout << contents;
    return 0;
}

或者,您可以读取文件的所有内容,删除不需要的任何字符并反转。为此,您可以在std :: remove_if中使用谓词函数。

#include <iostream>
#include <cctype>
#include <fstream>
#include <string>

int main()
{
    std::cout << "Please enter the filename: ";
    std::string filename;
    std::cin >> filename;

    std::string contents;
    std::ifstream file(filename, std::ifstream::in);

    if (file.good())
    {
        std::string contents((std::istreambuf_iterator<char>(file)),
                              std::istreambuf_iterator<char>());

        const std::string symbols = "&^# ";

        contents.erase(std::remove_if(contents.begin(), contents.end()
                       [&contents, &symbols](const char c) { return !(std::isalnum(c) || symbols.find(c) != std::string::npos); }),
                       contents.end() );

        std::reverse(contents.begin(), contents.end());
    }

    std::cout << contents;
    return 0;
}

答案 1 :(得分:-1)

int main()
{
    string fn;
    cin >> fn;

    ifstream fin(fn);

    if (fin.is_open())
    {
        /* for reading data character by character.. */

        string vec="";

        char temp;

        while (fin.get(temp))
        {
            vec += temp;
        }
        /*for writing data in reverse order*/

        for (int i = vec.size() - 1; i >= 0; i--)
        {
            cout << vec[i];
        }
    }

    return 0;
}

根据您的问题

“因此,我需要做的基本上是提示用户输入文件名,一次从文件中读取一个字母并将其存储在字符串中,然后编写一个函数以向后显示结果字符串的上下文。”

相关问题