VoltStatic
VoltStatic

Reputation: 25

I/O redirection in C++

I wrote a program that takes its input from a file (using ifstream), uses a bunch of std::getline to extract the data and manipulate it.

I want to use I/O redirection so that these lines can be used using std::cin (As if someone is typing this info). I looked it up but I didn't quite understand how I would implement it using the Visual Studio Community program. Any help is greatly appreciated.

Upvotes: 0

Views: 153

Answers (2)

VoltStatic
VoltStatic

Reputation: 25

I found the solution to my question!

I simply changed the following line of code from:

std::ifstream datastream(text file location);
while (std::getline(datastream, output_str)) {
.
stuff...
.
}

To:

while (std::cin(datastream, output_str));

Once I compiled my code with no errors and got my ./a.out, I typed in my compiler:

./a.out < text file

And that pretty much started inputting the file content into std::cin as if someone was typing it.

Upvotes: 0

Param Siddharth
Param Siddharth

Reputation: 958

I would suggest you to use a stringstream for that:

#include <iostream>
#include <sstream>

int main() {
    string z = "100";
    stringstream a("");
    a << z;
    int x;
    a >> z; // Extracts data; a works like cin would have if it were used to input data
    cout << z;
    return 0;
}

Upvotes: 1

Related Questions