Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

stuck in endless input loop

+4 votes
asked Dec 5, 2023 by Teddy (220 points)
I have this code

#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <vector>

std::string readFileIntoString(const std::string& filename);
void interpret(std::string file);
void lexer(std::string file);
void execute();

std::vector<std::string> tokens;

int main() {
    std::cout << "Enter the filename: ";
    std::string filename;
    getline(std::cin, filename);
    std::string fileContents = readFileIntoString(filename);
    
    interpret(fileContents);
    
    return 0;
}

std::string readFileIntoString(const std::string& filename) {
    std::ifstream file(filename);
    
    if (!file.is_open()) {
        
        std::cout<<"File could not be found";
        return "";
        
    }

    std::ostringstream oss;
    oss << file.rdbuf();

    return oss.str();
    
}

void interpret(std::string file){
    
    lexer(file);
    execute();
    
}

void lexer(std::string file){
    
    //Super basic lexer, going to add more later...
    std::string token;
    std::stringstream File;
    File.str(file);
    while(true){
        if(File.str().empty()){
            break;
        }
        File>>token;
        tokens.push_back(token);
    }
    
}

void execute(){
    
    int index = 0;
    for (int i = 0; i < tokens.size(); i++) {
        std::cout<<"test ";
    }
    
}

but it just gives me an endless supply of inputs

1 Answer

0 votes
answered Dec 13, 2023 by Peter Minarik (86,240 points)

but it just gives me an endless supply of inputs

Well, what is happening here is that you have an infinite loop, because of

if (File.str().empty())
{
    break;
}

will never terminate unless your file never ever hand any content in it.

Instead, you should probably check if you've reached the end of the stream. With these changes, your last two functions would look something like this:

void lexer(std::string content)
{
    //Super basic lexer, going to add more later...
    std::string token;
    std::stringstream stringStream(content);
    while (!stringStream.eof())
    {
        stringStream >> token;
        tokens.push_back(token);
    }
}

void execute()
{
    for (int i = 0; i < tokens.size(); i++)
    {
        std::cout << tokens[i];
    }
}
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...