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.

3
  • "my IDE dosen't allow that". Strange, which IDE do you use? Commented Aug 5, 2018 at 1:37
  • @Jarod42 It's a custom IDE made by the school. That's why :( Commented Aug 5, 2018 at 1: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 (stackoverflow.com/questions/3024197/…). Commented Aug 5, 2018 at 1:55

2 Answers 2

1

Maybe stringstream might help:

#include <iostream>
#include <sstream>


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

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

Demo

Sign up to request clarification or add additional context in comments.

3 Comments

You could use a raw string literal so that the OP can just copy and paste the contents of a file into the source code with the line breaks and everything.
@FeiXiang Could you explain how to do that?
@DevanshSharma: raw string literal is R"(some_text which may contain quote as " or backslash as \ )".
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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.