How do I read input .in files in command line on windows - c++

I completed my code but the problem is I don't know how to test it based on instructions given.
The instructor provided us with 3 input files with the following values:
file1: 33 20
file2: 5 7
file3: 18 15
I'm supposed to take these values and create event objects with these stored values. Problem is the instructor is giving the testing method on Ubuntu and she displayed how to input file in command line like:
./sApp < simulationShuffled3.in
So i'm just really confused as to how I'm suppose to get it working. I am currently using Windows console, VStudios and sublime text with a terminal attachment.
The code I'm currently using that's following from an example from my course notes is
while (getline(cin >> ws, aLine)) { // while (there is data)
stringstream ss(aLine);
ss >> arrivalTime >> processingTime;
Event newEvent = Event('A',arrivalTime,processingTime);
eventPriorityQueue.enqueue(newEvent);
}

Read input from stdin in Windows [&/or] Linux
You can do this in three ways:
In Command prompt (windows)
In Powershell (windows/linux)
In WSL & Linux
1: in Windows Cmd
type input.in | python file_requiring_input.py # in python
type input.in | go run file_requiring_input.go # in go
type input.in | node file_requiring_input.js # in js
javac file_requiring_input.java &&
type input.in | java file_requiring_input # in java
g++ file_requiring_input.cpp &&
type input.in | a.exe # in cpp
gcc file_requiring_input.c &&
type input.in | a.exe # in c
Another way
python file_requiring_input.py < input.in # in python
g++ file_requiring_input.cpp &&
a.exe < input.in # in cpp
2: in Powershell
gc .\input.in | python file_requiring_input.py # in python
g++ .\file_requiring_input.cpp ;
gc .\input.in | .\a.exe # in cpp
gc is short for Get-Content. Other aliases of gc are cat and type.
which means that all three names can be used as replacement or gc
3: use wsl for windows //Linux commands
cat input.in | python file_requiring_input.py # in python
g++ file_requiring_input.cpp &&
cat input.in | ./a.out # in cpp
another way
python file_requiring_input.py < input.in # in python
g++ file_requiring_input.cpp &&
./a.out < input.in # in cpp
have edited the code testing everything out hopefully. Do correct me if I am wrong or if anything more is to be added .
Also input.in is more generally a text file so you can create input.txt file as you wish and it would work the same

Well, as this is an assignment, I'm not going to provide you with a ready-made code. Rather, I'll just point you to the right direction.
In Windows, you can provide the arguments to your executable separated by space on Command Prompt like this:
C:\Assignment> Test.exe file1.in file2.in file3.in
And, it'll work on Ubuntu as well.
So, you need to study Command Line Arguments, File Handling, reading from file; and, you'll have to convert these strings read from files to integers.
Command Line Arguments: http://en.cppreference.com/w/c/language/main_function
File Handling: http://en.cppreference.com/w/cpp/io/basic_fstream
Here's a minimal example for reading from a file (std::ifstream):
I've a test file at C:\Test\Test.txt with the following contents:
11 22
12 23
23 34
Here's is main.cpp to test it:
#include <iostream>
#include <fstream>
#include <string>
int main( int argc, char *argv[] )
{
const std::string filename { R"(C:\Test\Test.txt)" };
std::ifstream ifs { filename };
if ( !ifs.is_open() )
{
std::cerr << "Could not open file!" << std::endl;
return -1;
}
int arrivalTime { 0 };
int processingTime { 0 };
while ( ifs >> arrivalTime >> processingTime )
{
std::cout << "Arrival Time : " << arrivalTime << '\n'
<< "Processing Time : " << processingTime << std::endl;
}
ifs.close();
return 0;
}
Output:
Arrival Time : 11
Processing Time : 22
Arrival Time : 12
Processing Time : 23
Arrival Time : 23
Processing Time : 34

Related

Issue with file redirection and coding in c++ using ubuntu linux

I am trying to complete an assignment where I create a numbers.txt file that has one line with six numbers without any addition or subtraction. I have to write a program(sum.cpp) that adds the numbers using cin as an input. I have instructions to go to linux and type in $./sum < numbers.txt and it should print sum.
I tried doing that and multiple variations of the code and got a blank screen. When I did it in another compiler I got 32764 which is way off from the sum.
#include <iostream>
using namespace std;
int main()
{
int sum = 0;
int input= 0;
while(cin>>input)
{
sum+=input;
}
cout << sum << endl;
return 0;
}
Expected Results :
If you have a file numbers.txt that contains:
10 15 16 -7 102 345
then if you redirect it into the program, it should report:
$ ./sum < numbers.txt
481
Please try running the following commands, after placing both sum.cpp and numbers.txt in the same directory
g++ sum.cpp -o sum.out
chmod +x ./sum.out
./sum.out < numbers.txt

C++ exec executed bash scripts stops randomly

I'm executing a bash script via execvp but the script stops execution half-way.
Have a look at my code:
int main()
{
char* params[2];
//First Parameter has to be the executable path
params[0] = (char*) ::malloc(sizeof(char) * 40);
::strcpy(params[0], "/home/test.sh");
//execv needs an null pointer as last argument
params[1] = NULL;
//Execute target executable
::execvp(params[0], params);
//Only if ::exec() returns: output error
std::cout << "Exec Failed!";
exit(1);
}
I used the following bash script for testing:
#!/bin/bash -vx
echo "1" >> /home/out.txt
echo "2" >> /home/out.txt
echo "3" >> /home/out.txt
echo "4" >> /home/out.txt
echo "5" >> /home/out.txt
exit 0
Most times the script doesn't even execute, means no file is being created or nothing is being written into an existing file. Somtimes, however the script executes partially or even complete meaning the textfile contains
1
up to
1
2
3
4
5
But no matter what happens inside the bash script the application always exits with error code 0.
Why is this happening?
If i execute the bash script manually everything works fine reaching the end of my script every time. Therefore, i assume it has to do something with my execvp call instead of the bash script.
I'm running, therefore tested the program on an beaglebone black system (am335x) with debian 8.6.
here is what I did to make this program work:
Note: I re-wrote it in C
The proposed C code:
#include <stdio.h> // perror()
#include <stdlib.h> // exit()
#include <string.h> // strcpy()
#include <unistd.h> // execvp()
int main( void )
{
char* params[2];
//First Parameter has to be the executable path
params[0] = "/home/rkwill/rtest.sh";
//execv needs an null pointer as last argument
params[1] = NULL;
//Execute target executable
execvp(params[0], params);
perror( "execvp failed" );
exit(1);
}
then, in my user directory: /home/rkwill/
touch rtest.sh
then edited 'rtest.sh' to contain:
#!/bin/bash -vx
# generate file if not already in existence
touch /home/rkwill/out.txt
echo "1" >> /home/rkwill/out.txt
echo "2" >> /home/rkwill/out.txt
echo "3" >> /home/rkwill/out.txt
echo "4" >> /home/rkwill/out.txt
echo "5" >> /home/rkwill/out.txt
exit 0
Then made the bash script executable via
chmod 777 rtest.sh
Note: I used the directory /home/rkwill because I do not have permission to write in the /home directory.
the first time I ran the program the resulting 'out.txt file contained
1
2
3
4
5
each successive run appended a repeat of the above output to 'out.txt'

Redirecting I/O only with <iostream> [Windows]

[#tl;dr] I have Visual Studio Ultimate 2013 and Eclipse Neon v2(C++),
and I need to redirect the output of my program using DOS format, but
I have no idea how.
Im on Windows btw.
OK.. so I have this class assignment where I have to write a program like this:
#include <iostream>
#include <string>
using namespace std;
/* Check if the Character is lower case or not */
bool checkLowerCase(char c) {
if (c >= 'a' && c <= 'z') return true;
return false;
}
/*
* If there is any lower case letter, it will replace it will a upper case.
* example:
* "Tauros" will become "TAUROS"
* "auHU" will become "AUHU"
*/
string fixer(string s)
{
char right = ('a' - 'A');
string a = s;
for (unsigned int i = 0; i < a.length(); i++)
{
if (checkLowerCase(a[i])) {
a[i] = a[i] - right;
}
}
return a;
}
int main(void)
{
while (1) //infinite loop
{
string line;
getline(cin, line);
if (!cin) { //Professor wants us to only check end of input like this
return 0;
}
line = fixer(line);
cout << line << endl;
}
}
The input was:
aaaaaa
bbbbbb
cccccc
The output was:
aaaaaa
AAAAAA
bbbbbb
BBBBBB
cccccc
CCCCCC
Thanks for reading this far. Ok, so here's my problem.
The output is all messed up, so I need to redirect the output somewhere else (at least for testing).
I know how to do that using , , holding each line in a Array of String, reallocating if needed and then print what is on the array, but, unfortunately, my lecturer demanded us only to include and
Ohh, I dont know if it will matter, but we may not use char*, only the class string.
My lecturer told us that we have to use DOS format. But I have no clue how to do that. If someone can tell me how to do either redirect the input or the output is finee...
I have in my PC both Eclipse C++ (working glitchy) and Visual Studio Ultimate 2013 (working fine).
[Edit] Im on Windows.
AGAIN: I may only include and
For more information, here's his slide on DOS format.
*For testing purposes one redirect to/from a file
*DOS formatting will have unexpected consequences
– The end-of-line is the CR-NL combination
– A line read from the file will end with CR
– The CR character is the command to erase the
previous line!
./main < infile.txt Input is from infile.txt
./main > outfile.txt Output is to outfile.txt
./main < infile.txt > outfile.txt Both input and output are redirected
OK, so... I found instructions that helped me here:
https://msdn.microsoft.com/en-us/library/ms235639.aspx
I opened my project folder in the VisualStudio, created 2 files.
input.txt
output.txt
I opened the Developer Command Prompt for VS2013 that I had in my PC.
cd ["C://my_project_path"] //go to my project folder
cl /EHsc file.cpp
/*
cl /EHsc will compile my program (I think it only compiles one file at a time.
I have yet to test it).
*/
file < input.txt > output.txt // this command will run my program
So when I run my program like this... Instead of waiting for an input from keyboard, my program will read input.txt as the standard input. And when I try to print something to the output, it will write on the output.txt instead.
[EDIT] at the end of the link I pasted, there are explanations on how to compile multiple files and what exacly does the /EHsc do exacly

How do I execute a string as a shell script in C++?

I'm writing a program that needs to be able to execute a shell script provided by the user. I've gotten it to execute a single shell command, but the scripts provided will be more complicated than that.
Googling got me as far as the following code snippet:
FILE *pipe;
char str[100];
// The python line here is just an example, this is *not* about executing
// this particular line.
pipe = popen("python -c \"print 5 * 6\" 2>&1", "r");
fgets(str, 100, pipe);
cout << "Output: " << str << endl;
pclose(pipe)
So that this point str has 30 in it. So far so good. But what if the command has carriage returns in it, as a shell script file would, something like the following:
pipe = popen("python -c \"print 5 * 6\"\nbc <<< 5 + 6 2>&1", "r");
With this my goal is that str eventually have 30\n11.
To put another way, assume I have a file with the following contents:
python -c "print 5 * 6"
bc <<< 5 + 6
The argument I'm sending to popen above is the string representation of that file. I want to, from within C++, send that string (or something similar) to bash and have it execute exactly as if I were in the shell and sourced it with . file.sh, but setting the str variable to what I would see in the shell if it were executed there, in this case, 30\n11.
Yes, I could write this to a file and work it that way, but that seems like it should be unnecessary.
I wouldn't think this was a new problem, so either I'm thinking about it in a completely wrong way or there's a library that I simply don't know about that already does this.
use bash -c.
#include <stdio.h>
int main()
{
FILE *pipe = popen("bash -c \"echo asdf\necho 1234\" ", "r");
char ch;
while ((ch = fgetc(pipe)) != EOF)
putchar(ch);
}
Output:
asdf
1234
(I've test on cygwin)

Pipe an input to C++ cin from Bash

I'm trying to write a simple Bash script to compile my C++ code, in this case it's a very simple program that just reads input into a vector and then prints the content of the vector.
C++ code:
#include <string>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<string> v;
string s;
while (cin >> s)
v.push_back(s);
for (int i = 0; i != v.size(); ++i)
cout << v[i] << endl;
}
Bash script run.sh:
#! /bin/bash
g++ main.cpp > output.txt
So that compiles my C++ code and creates a.out and output.txt (which is empty because there is no input). I tried a few variations using "input.txt <" with no luck. I'm not sure how to pipe my input file (just short list of a few random words) to cin of my c++ program.
You have to first compile the program to create an executable. Then, you run the executable. Unlike a scripting language's interpreter, g++ does not interpret the source file, but compiles the source to create binary images.
#! /bin/bash
g++ main.cpp
./a.out < "input.txt" > "output.txt"
g++ main.cpp compiles it, the compiled program is then called 'a.out' (g++'s default output name). But why are you getting the output of the compiler?
I think what you want to do is something like this:
#! /bin/bash
# Compile to a.out
g++ main.cpp -o a.out
# Then run the program with input.txt redirected
# to stdin and the stdout redirected to output.txt
./a.out < input.txt > output.txt
Also as Lee Avital suggested to properly pipe an input from the file:
cat input.txt | ./a.out > output.txt
The first just redirects, not technically piping. You may like to read David Oneill's explanation here: https://askubuntu.com/questions/172982/what-is-the-difference-between-redirection-and-pipe