Python3: Popen with infile and outfile doesn't stop at the end of infile - python-3.x

I want to call an interactive command line program (c++ using cin/cout).
I want to define the input through an input file.
I want the output to be written in an output file.
After all the inputs inside the input file are used, the executed program should be killed, even, if it would naturally run on.
Target machine is windows 10.
To achieve this, I tried using the following:
from subprocess import *
with open("input.txt", "r") as ifile:
with open("output.txt","w") as ofile:
p = Popen(["./example.exe"], stdin=ifile, stdout=ofile, stderr=None, universal_newlines=True )
p.wait()
I also tried it with call instead of Popen, but same result.
I also tried p.stdin.write/ readline, but everything I came up with hangs (eg, because the exe program waits inside cin) or mashes up the order.
This is my cpp code for testing:
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
string inputString("");
for (int i = 0; i< 200; ++i){
cout << "type a number: " << endl;
cin >> inputString;
if(inputString == "1"){
cout << "eins" << endl;
} else if (inputString == "2"){
cout << "zwei" << endl;
} else if (inputString == "blub"){
break;
}
else{
cout << "unknown" << endl;
}
}
return 0;
}
I would expect this the python code to stop running, after all input lines inside the input file are used.
Instead, the last line gets repeatedly used as input (arbitrary* number of times) or the program gets terminated in the middle.
*arbitrary: Outfile always has exactly 400 lines.

Related

How do I convert strings of numbers, coming from a .txt file into an int array using stoi::("string")

I've been trying to take a .txt document with three number entries, read those entries as strings and convert those entries in ints, then put them into an int array, but had no success in doing so and i have no clue as to why. Note that the entries as well as some variable names are pre determined by the assignment, additionally we have to use the std::stoi("string") command, which i am not familiar with nor has any syntax been provided to us (which is especially strange since we are usually not allowed to stray to far from the lecture material)
What I excpected to happen is that the numbers from the .txt file were converted into an array, however what actually happened is that an "unhandled exception" (my apologies if that term does not make sanes we have to programm in our native language) occured and the string library opened itself, marking the error on line 107. The problematic line in my code seems to be "auftraegearray[i++] = std::stoi(MengeanAuftraegen);"
int main()
{
std::fstream Auftraege;
Auftraege.open("Auftraege37.txt", std::ios::out);
Auftraege << "10" << std::endl;
Auftraege << "1" << std::endl;
Auftraege << "20" << std::endl;
Auftraege.close();
int i = 0;
int auftraegearray[4];
std::string MengeanAuftraegen;
Auftraege.open("Auftraege37.txt", std::ios::in);
while (!Auftraege.eof())
{
getline(Auftraege, MengeanAuftraegen);
std::cout << MengeanAuftraegen << std::endl;
auftraegearray[i++] = std::stoi(MengeanAuftraegen);
}
Auftraege.close();

Why cout seems not act like line buffering

`
#include<iostream>
#include<Windows.h>
using namespace std;
int main()
{
cout << 'b';
Sleep(5000);
return 0;
}
`
The b is printed onto the screen immediately.
But the cout is acting in line buffering.
The b is expected to be printed after 5 seconds when "return 0;" flashes the I/O buffer by me.

Reading and writing different files in their own threads from my main loop in C++11

I am trying to understand, then, write some code that has to read from, and write to many different files and do so from the main loop of my application. I am hoping to use the C++11 model present in VS 2013.
I don't want to stall the main loop so I am investigating spinning off a thread each time a request to write or read a file is generated.
I've tried many things including using the async keyword which sounds promising. I boiled down some code to a simple example:
#include <future>
#include <iostream>
#include <string>
bool write_file(const std::string filename)
{
std::cout << "write_file: filename is " << filename << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
std::cout << "write_file: written" << std::endl;
return true;
}
int main(int argc, char* argv[])
{
const std::string filename = "foo.txt";
auto write = std::async(std::launch::async, write_file, filename);
while (true)
{
std::cout << "working..." << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(100));
std::cout << "write result is " << write.get() << std::endl;
}
}
I'm struggling to understand the basics but my expectation would be that this code would constantly print "working..." and interspersed in the output would be the write_file start and end messages. Instead, I see that the write_file thread seems to block the main loop output until the timer expires.
I realize I need to also consider mutex/locking on the code to actually write the file but I would like to understand this bit first.
Thank you if you can point me in the right direction.
Molly.
write.get() will wait for the async task to finish. You want to use wait_for() instead:
do {
std::cout << "working...\n";
} while(write.wait_for(std::chrono::milliseconds(100)) != std::future_status::ready);
std::cout << "write result is " << write.get() << "\n";

How to scan strings with spaces in cpp in a new line?

enter image description here3(no of cases)
hello world
a b c d
data structures and algorithms.
Let say above is the given input format.Each string starts in a new line.Can i know how to read in the above way in cpp.I tried with getline function.It didn't work.
The getline method should work just fine. The following code works fine.
#include <iostream>
using namespace std;
int main(){
string s[3];
getline(cin, s[0]);
getline(cin, s[1]);
getline(cin, s[2]);
cout << s[0] << endl << s[1] << endl << s[2];
return 0;
}
EDIT:
After your clarification, it seems that the problem is actually that the buffer is not being cleared properly. So just use cin.ignore(); after cin >> t;
Refer to the code below:
#include <iostream>
using namespace std;
int main(){
int t;
cin >>t;
cin.ignore(); // This should clear the input buffer
string s;
getline(cin, s);
cout << s << endl;
return 0;
}

Error on the first code I wrote on C++. Don't know what's happening

I wrote this code for my class and when i debug it runs but shuts down within seconds i dont know what i'm doing wrong here. I am really new to C++ so.
here is the code:
#include "stdafx.h"
#include<iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
double gallons;
double startmile;
double endmile;
double totalmilestravelled;
cout << "This Program Calculates your vehicle's gas mileage on this trip\n" << endl;
cout << "What is the number of gallons consumed on the trip: ";
cin >> gallons;
cout << "\nWhat was your ending mile?";
cin >> endmile;
cout << "\nWhat was your starting mile?";
cin >> startmile;
totalmilestravelled = endmile-startmile;
double mpg = totalmilestravelled/gallons;
cout << "your gas mileage is: " << mpg << endl;
return 0;
}
and this is the error:
The program '[9848] gasmileage.exe: Native' has exited with code 0 (0x0).
That's not an error. The program exited normally. When you run a program, it executes and exits with an exit code specified by the program. In this case you return 0, so the program exits with code 0. If you want the program to "pause" to allow you to see the result of the program before it closes, add this just before the return statement:
cin.ignore(128, '\n');
cin.get();
The first line discards newlines that were left over in the standard input. Don't worry about this too much until you learn more about the input stream, but you need to do this if you are attempting to read a string after reading numeric input from the user. The second line will prompt the user for some input (push return). You don't care what the input is, and you aren't going to do anything with the input. You just want to force the program to wait for user input so that you can see what's going on before continuing with the program (which in this case the program immediately exit).
Think about programs that say "Press any key." It's the same thing we're doing here. Giving the user a moment to view the output.

Resources