【问题标题】:how to read file and print in reverse order using stack C++如何使用堆栈 C++ 以相反的顺序读取文件和打印
【发布时间】:2019-01-07 07:24:34
【问题描述】:

我必须一次读取每个单词的文本文件,然后将该单词推送到堆栈,然后一次弹出每个单词以在显示器中打印。我尝试了以下代码,但运行程序后,编译器只显示空白屏幕而没有错误。 笔记: 我不允许使用类或结构或使用 STL 来实现堆栈。堆栈必须使用固定大小的单词数组和用于指示堆栈顶部的索引整数来实现

我的文本文件是这样的:

one two three four five
six seven and so on

输出应该是:

no os dna neves xis ...

main.cpp

using namespace std;

char word;
void push(char);
void pop();
void displaywords();

int count = 0;
const int arr_Size=50;
string stack[arr_Size];

int main()
{
    //string word;
    ifstream infile;
    infile.open("data.txt");
    if(!infile)
    {
        cerr << "An error occurred while opening the file.";
        exit(1);
    }

    do
    {
        cin >> word;
        if (infile.fail())
            break;
        cout << word;   
        push(word);     
    }while(infile.eof());
    infile.close();

    while(stack!=NULL) // trying to write code for stack is not null
    {
        displaywords();
        pop();
    }
    return 0;
}

void push(char word)
{
    count = count + 1;
    stack[count] = word;
}

void displaywords()
{
    cout << "PUSHED " << " " << stack[count] << "   ." << endl;
}

void pop()
{
    count = count - 1;
}

【问题讨论】:

标签: c++ stack file-handling


【解决方案1】:

std::cin 从标准输入读取。您不会从流缓冲区中获取任何内容 - 它正在等待用户输入。

【讨论】:

    【解决方案2】:

    您的代码有很多问题。一个明显的问题是阅读循环以while(infile.eof()) 作为其条件。这几乎肯定不是你想要的。 while(!infile.eof()) 可能是您所想的,但这也不能真正正确/可靠地工作。

    您也在打开infile,但是当您阅读时,您尝试从cin 阅读而不是infile

    您还尝试使用while(stack!=NULL),其明显意图是读取直到堆栈为空——但stack 是一个数组。它永远不会比较等于 NULL。

    由于您使用的是 C++,因此我将使用标准容器(例如,std::vectorstd::deque,带有或不带有 std::stack 适配器)。这个一般顺序上的东西应该更接近一点:

    std::vector<std::string> strings;
    std::infile("some file.txt");
    std::string word;
    
    while (infile >> word)
        strings.push_back(word);
    
    while (!strings.empty()) {
        std::cout << strings.back();
        strings.pop_back();
    }
    

    【讨论】:

    • 我不允许使用类或结构或使用 STL 来实现堆栈。堆栈必须使用固定大小的单词数组和用于指示堆栈顶部的索引整数来实现
    • @muzzi: 好吧,那就继续吧——虽然如果是我,我仍然会创建一个我自己的 stack 类,所以剩下的代码就可以处理了具有抽象级别的堆栈(推送,弹出。顶部)。哦,根据对问题的编辑,您真的想一次读取一个字符,并将单个字符放在堆栈上,而不是整个单词。
    【解决方案3】:

    那是因为您正在尝试从cin 读取。将do 块中的cin 更改为infile

    【讨论】:

      猜你喜欢
      • 2020-08-18
      • 1970-01-01
      • 1970-01-01
      • 2011-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多