【问题标题】:c++ "not declared in this scope" errorc ++“未在此范围内声明”错误
【发布时间】:2015-12-07 00:35:04
【问题描述】:

我不断收到错误消息,告诉我我没有在 if(!buffer.empty) 循环下的范围内定义缓冲区。

有人对我应该做什么以及我做错了什么有任何建议吗?

#include <fstream>  // this is to import the ifstream and ofstream objects
#include <iostream>  // this is to import the cin and cout objects
#include <stack> 
using namespace std;

// precondition: theFile refers to a stream that has been opened already
// postcondition: the contents of the file have been read and output to the console

void read_file( ifstream& theFile ) {
    stack buffer;  // this string will read in the buffer from the file 

    //while there are still things in the file to read in, read it in and output to console.
    while( theFile.eof() == false ) {
        buffer.push(theFile);
        //cout << buffer << endl; // print the string and a newline 
    }

    if( !buffer.empty() ) {
        cout << buffer.top() << endl;
        buffer.pop();
    }else{
        cout << "uh oh!" << endl;
    }
}

int main() {
    ifstream theInputFile;
    theInputFile.open("input.txt"); // Open the file with the name "inputFile.txt". 

    // pass the file stream into the read_file() function. 
    read_file( theInputFile );
    theInputFile.close();
}

【问题讨论】:

  • std::stack 是一个类模板。见en.cppreference.com/w/cpp/container/stack
  • std::stack 是一个模板,它需要参数。更重要的是,您为什么要尝试将 std::ifstream 推入堆栈?为什么首先要使用堆栈?
  • 我的教授已经给出了部分代码。我必须合并一个堆栈或递归才能让文件读取其中的内容,但要向后读取。

标签: c++ loops scope undefined


【解决方案1】:

所以缓冲区是一个堆栈。堆什么? stack&lt;int&gt; buffer 可以工作,或者stack&lt;char&gt; buffer,或者任何你需要的东西。

我不知道你需要一堆什么。我注意到你在推theFile,这没有意义。这可能是有道理的:

while( theFile.eof() == false ) 
{
    theFile >> something;
    if (! theFile) break; //if we reached eof or had other problems, just quit
    buffer.push(something);
}

取决于您想对空格做什么,如果 somethingchar, char*string

【讨论】:

  • juanchopanza 提出了一个很好的观点:原始代码和我的修复都没有检查something 中的阅读是否有任何问题。我会适当地编辑帖子。
猜你喜欢
  • 2022-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多