Devansh Sharma
Devansh Sharma

Reputation: 43

Get Input from the source code itself C++

I want to do something like this

// Example program
#include <iostream>

/*

//IF 
//ASKED FOR INPUT :
//12

*/ 

int main()
{
  int myInt;
  std::cin >> myInt;
  std::cout << myInt;
}

I want this snippet to print 12

I want the code to do something like what the commented part states.

I know I can use standard output and just type it in there. But, my IDE dosen't allow that and I don't want to read it from a file either. Any suggestions?

Before, I thought I can use #defineto redefine the purpose of cin and read from the top of the file instead. But, I'm not sure if it would work or how to implement it either.

Upvotes: 0

Views: 252

Answers (2)

selbie
selbie

Reputation: 104549

You could have two different builds based on a #define value. Use stringstream as an input:

#include <iostream>
#include <sstream>

#define USING_FAKE_STREAM
#ifdef USING_FAKE_STREAM
    std::stringstream g_ss;
    void initStream()
    {
        g_ss << "12\n";
    }

    std::istream& getInputStream()
    {
        return g_ss;
    }
    #else
    void initStream()
    {
    }

    std::istream& getInputStream()
    {
        return std::cin;
    }
#endif

int main()
{
    initStream();

    auto& inputStream = getInputStream();

    inputStream >> myInt;
    std::cout << myInt;

    return 0;
}

Upvotes: 0

Jarod42
Jarod42

Reputation: 217358

Maybe stringstream might help:

#include <iostream>
#include <sstream>


int main() {
    std::stringstream ss("42");

    int i;
    ss >> i;
    std::cout << i;
}

Demo

Upvotes: 1

Related Questions