Issue
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 <.
Solution
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";
}
}
Answered By - Martin York Answer Checked By - Candace Johnson (WPSolving Volunteer)