0

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.

  • *"my IDE dosen't allow that"*. Strange, which IDE do you use? – Jarod42 Aug 05 '18 at 01:37
  • @Jarod42 It's a custom IDE made by the school. That's why :( – Devansh Sharma Aug 05 '18 at 01:42
  • One option is to receive the value as a program parameter. You would need to use `int main(int argc, char **argv) {}` and configure your IDE to pass a parameter when it runs the code (https://stackoverflow.com/questions/3024197/what-does-int-argc-char-argv-mean). – HugoTeixeira Aug 05 '18 at 01:55

2 Answers2

1

Maybe stringstream might help:

#include <iostream>
#include <sstream>


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

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

Demo

Jarod42
  • 203,559
  • 14
  • 181
  • 302
0

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;
}
selbie
  • 100,020
  • 15
  • 103
  • 173