Reading arguments from a text file using < - c++

I have a txt file called test.txt that looks like this,
hi this is a test
and I have a c++ file called selection_sort.cpp that looks like this,
#include <iostream>
using namespace std;
int main(int argc, char *argv[]) {
cout << argc << endl;
for (int i = 0; i < argc; i++) {
cout << argv[i] << endl;
}
return 0;
}
right now when I compile my program in my terminal with
g++ selection_sort.cpp -o selection_sort
and then try and print out all of of the arguments I am trying to pass using my code like this
./selection_sort < test.txt
but it only outputs
./selecton_sort
I would like it to output
./selection_sort
hi
this
is
a
test
What am I missing or doing wrong? I need to use the <.

What am I missing or doing wrong? I need to use the <.
This is a shell operator that sends the content of the file to the standard input of the application.
./app < text.file
Will read the file text.file and send the conent to the standard input of the application app. In C++ you can read the standard input via std::cin.
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
std::string word;
while (std::cin >> word) {
std::cout << word << "\n";
}
}

< in bash is used to redirect input. In other words, it redirects the standard input for your process to the file. However, command line arguments (e.g. argv arguments) are not read through standard input, so you cannot capture them from a file by redirecting input.
Rather, they are provided as arguments when running the command in bash to begin with. You can accomplish your goal like so:
./selection_sort $(cat test.txt)
cat is for concatenating files, but if you supply it just one file, it will just output the contents of the file through standard out. The $(x) operation will execute the x command in a subshell, capture its standard output (which in this case is the contents of the file), and then do variable substitution to replace $(x) with said contents.
Edit:
Or, you can just change the way the arguments are accepted, so that they are accepted via standard input. It depends on how you want to be able to run the program.

Related

Qt | QProcess | Write line to console application

I am using QProcess to communicate with console application: i am writing some words and read outputs. But i want to write line via QProcess. For example, i have the next console app:
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;
int main(int argc, char* argv[])
{
string action;
do
{
cout << "(test)";
cin >> action;
cout << action;
if(action.length() > 10)
{
cout << "\t very long string";
}
cout << endl;
}
while(action != "exit");
return 0;
}
So, i can't pass parameters via QProcess::exec or QProcess::start, because it pass parameters to char* argv[]. I should pass it after launching QProcess. I've tried use QProcess::write, but there are problem: if i use
process.write("oneWord\n");
i'll get success. But if i use
process.write("several words\n");
my program will write all this word separately and it looks like
process.write("several\n");
process.write("words\n");
Console application doesn't recognize it as one string. I've tried using different ways: write line in double brackets,
process.write("\"several words"\\n");
and
process.write("\"several words\n""\);
use protected methods QIODEvice::setOpenMode and set QIODevice::Text flag, use QDataStream, use special symbols like \r, \n, \t and different combination. Also, i tried to use multiple QProcess::write
process.write("several");
process.write("words\n");
I know, that QProcess inherits QIODevice and there are opportunity to deal with it like a file (input & output). But it doesn't matter if words will be written to file separately in file. In my case, it does matter.
Can anyone help me?

How to take characters in a text file as arguments

I'm fairly new to C++, I'm trying to figure out how to take in arguments from a text file and use them in my program.
So if I wanted to include a text file whatever.txt in a command, it would use specified lines as arguments.
Like if the text file looked like this:
1 2
and I wanted to use 1 and 2 from it, as arguments in my program.
So far from what I've gathered, I need something akin to this:
int main (int argc, char const *argv[]) {
to start, but not sure where to go from here.
I'm trying to mess around with certain stuff, but I'm still pretty new and outside of loops and things I can't do much with the language yet!
Short of giving you the code that will do this for you (which would ruin the fun of learning how to do these things), the steps I would follow would be:
Take one argument from the command line as the file name you want to read the information from. Think of running your script like this:
$ ./myscript whatever.txt
Then, argv[0]="./myscript" and argv[1]="whatever.txt".
Open the file (perhaps ifstream would be good for this).
Loop through each line of the file (maybe using getline to put each line into a string)
Parse each line of the file (I've seen stringstream used for filling variables from a string).
Hopefully that will help you along your way.
int main(int argc, char *argv[])
after retrieving files names in the main function you should open each file and retrieve its contents
Sample code
int main(int argc, char* argv[])
{
for(int i=1; i <= argc; i++) // i=1, assuming files arguments are right after the executable
{
string fn = argv[i]; //filename
cout << fn;
fstream f;
f.open(fn);
//your logic here
f.close();
}
return 0;
}
https://stackoverflow.com/a/30141375/3323444
argc is the number of arguments passed in to your program, argv is an array of character strings holding the names of arguments passed in.
at least there's one parameter passed in which is argv[0] which is name of program.
after building this code run it form a command prompt as:
main.exe data.txt
or simply DRAG AND DROP file "data.txt" on your main.exe
main.exe is your program, data.txt is text file containing data you want to use
#include<iostream>
#include<fstream>
int main(int argc, char* argv[])
{
char c;
if(argc < 2)
{
std::cout << "No file passed to program!" << std::endl;
return 1;
}
std::ifstream in (argv[1] , std::ios::in);
if(!in)
std::cout << "Unable to read file: " << argv[1] << std::endl;
while(in >> c)
std::cout << c << std::endl;
in.close();
std::cin.get();
std::cout << std::endl;
return 0;
}

In cpp how to use getline() get full sentence without interactive input?

Like the following codes, how to get the whole sentences by getline() function if there is no interactive input?
right now, the input&output is:
input "today is a good day"
output "today"
#include <iostream>
#include <pthread.h>
using namespace std;
string value;
int main(int argc, char *argv[]){
value=argv[1];
cout << value;
return 0;
}
try this
string s;
for(int i = 1; i < argc; i++) {
s += argv[i];
s += " ";
}
Usually you'd handle this in the calling environment, by piping your input.
$ myProgram
<console waiting for input>
vs
$ echo "my input here!" | myProgram
or
$ cat /var/someFile | myProgram
or even
$ netcat 192.168.0.15:80 | myProgram
No code changes required.
Command line arguments are intended for switches and options that alter the program's behaviour.

Passing text file to standard input

The following code is part of a larger translator program. The code below asks the user to type a line and than just writes it back. Is there a way that instead of writing a single line each time, I can just pass in a whole file etc 'translate.txt' in standard input and the program can write it back line by line and produces an error when the end of line is reached ?
#include <iostream>
#include <string.h>
#include<stdio.h>
#include<fstream>
using namespace std;
using namespace std;
void PL() {
char line[BUFSIZ];
while( cin.good() ) {
cout<<"Type line now"<<endl;
cout<<"\n";
cin.getline(line, sizeof(line));
cout<<"\n"<<endl;
string mystring = string(line);
// supposed to Parsing string into words and translate//
//but just reading back input for now//
cout<<"You typed:"<<mystring<<endl;
cout<<"\n"<<endl;
}
}
int main() {
PL();
}
Do you expect a way to pass a file to your program?
executable < file
This code works well for me:
void PL() {
string line;
while(cin) {
cout<<"Type line now";
if(std::getline(cin,line)) {
// supposed to Parsing string into words and translate//
//but just reading back input for now//
cout<<"You typed:"<<line<<endl;
}
}
}
Note that the stdin there is actually passed to the program from the shell as mentioned:
$ executable < file
If you want to pass arbitrary types of streams created from outside this function, you'll need something like
void PL(std::istream& is) {
string line;
while(is) {
cout<<"Type line now";
if(std::getline(is,line)) {
// supposed to Parsing string into words and translate//
//but just reading back input for now//
cout<<"You typed:"<<line<<endl;
}
}
}
int main() {
std::ifstream is("mytext.txt"); // hardcoded filename
PL(is);
return 0;
}
or alternatively
int main(int argc, char* argv[]) {
std::istream* input = &std::cin; // input is stdin by default
if(argc > 1) {
// A file name was give as argument,
// choose the file to read from
input = new std::ifstream(argv[1]);
}
PL(*input);
if(argc > 1) {
// Clean up the allocated input instance
delete input;
}
return 0;
}
There are certainly more elegant solutions
and calling from the command line:
$ executable mytext.txt
Your shell will have a way to pass a file in over stdin. So for example, if you are on a bourne-compatible shell you can run
translate < translate.txt
(assuming your program is compiled to a binary named translate). This is assuming you want to start the program interactively, i.e. from a shell.
If you want to automatically spawn this program from another program you wrote, it depends on your OS. On POSIX operating systems, for example, you will want to open the file and dup2 the resulting file descriptor into STDIN_FILENO after forking but before calling one of the exec family functions.

Redirecting input and output files on Unix and C++ using stdio

I need to do this:
$ ./compiledprog.x < inputValues > outputFile
so that I read from the file inputValues which for our case might just be \n separated int values or whatever. Then anything printf()'d goes into outputFile. But what's this called, technically speaking, and where can I find a demo of doing this.
As noted by others, it's input/output redirection.
Here's an example program that would copy the standard input to the standard output, in your example copy the contents from inputValues to outputFile. Implement whatever logic you want in the program.
#include <unistd.h>
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
using std::cerr;
#include <string>
using std::string;
int main(int argc, char** argv) {
string str;
// If cin is a terminal, print program usage
if (isatty(fileno(stdin))) {
cerr << "Usage: " << argv[0] << " < inputValues > outputFile" << endl;
return 1;
}
while( getline(cin, str) ) // As noted by Seth Carnegie, could also use cin >> str;
cout << str << endl;
return 0;
}
Note: this is quick and dirty code, which expects a well behaved file as input. A more detailed error checking could be added.
This is called I/O redirection.