C++ capture command line entered and output line by line - c++

I'm writting a c++ program and I am looking to capture the inputs from command line. For each argument that is entered in the command line it is to be captured. The program will capture every command line until the user enters END. The program will then provide an output of each commandline argument that was entered. Example: User enters ./program to run this program. ./program is captured. User then enters test this is then captured user then enters arg then END. The program then outputs
./program
test
arg
This is what I found for a resource I just don't know how to fully implement and loop http://www.cplusplus.com/articles/DEN36Up4/
Below is what I have so far, just not sure of the for loop waiting for the END
thanks!
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
std::cout << "Enter your command line \n and to stop enter END" << std::endl;
for (int i = 0; i < count; ++i)
{
/* code */
}
// Once user types END then arguments entered in will display
std::cout << << std::endl;
return 0;
}

Take a look at cin and getline
Sample code (not tested):
string command_list;
while(true) {
string input;
getline (cin, input);
if(input.compare("END") == 0)
break;
else
command_list.append(input);
}

Related

While loop will only terminate if I use CTRL + C on the terminal

The prompt of the question is:
Write a program that prompts the user to input the name of a text file and then outputs the number of words in the file. You can consider a “word” to be any text that is surrounded by whitespace (for example, a space, carriage return, newline) or borders the beginning or end of the file.
I have successfully gotten the program to count how many words are in a file; no issues there.
#include <fstream>
#include <iostream>
#include <cstdlib>
#include <string>
int main()
{
char file_name[16];
std::ifstream in_stream;
int count = 0;
char ch;
bool lastWasWhite = true;
std::string next;
// Ask the user for the file name
std::cout << "What is the name of the file? ";
std::cin >> file_name;
in_stream.open(file_name);
// See if we can open the file
if (!in_stream.is_open()) {
std::cout << "Something went wrong when opening your file.";
exit(1);
}
// Read the file, one character at a time
while (in_stream >> next) {
do {
std::cin.get(ch);
}
while (ch != ' ' && ch != '\n' && ch != '\t');
++count;
}
in_stream.close();
std::cout << "The file " << file_name << " contains " << count << " words." << std::endl;
return 0;
}
The only problem is that the only way for the program, or I think the "while loop" to finish, is for me to hit CTRL + C on the terminal so it force stops. Then I get the result I want.
This is my first post, so please let me know if there is any other information you would like to see.
Your outer loop is reading words from the file and counting them just fine (operator>> handles the whitespace for you).
However, your outer loop is also running an inner loop that is reading user input from stdin (ie, the terminal). That is where your real problem is. You are waiting on user input where you should not be doing so. So, simply get rid of the inner loop altogether:
while (in_stream >> next) {
++count;
}
That is all you need.

Reading a text file into a struct array c++

This is for a homework assignment, but what I am presenting is a small test program for a chunk of my assignment.
Starting out, I am to have a list of songs in file "songs.txt". My current file looks like this.
Maneater;4;32
Whip It;2;41
Wake Me Up Before You Go-Go;3;45
The file simply contains a song title, and the duration in minutes and seconds, with the title, minutes, and seconds separated by semicolons. The full file is supposed to contain the Artists and Album as well, all separated by semicolons. Anyways, the code.
#include<iostream>
#include<cstring>
#include<fstream>
#include<cstdlib>
using namespace std;
const int CAP = 100;
const int MAXCHAR = 101;
struct songInfo
{
char title[CAP];
char durMin[CAP];
char durSec[CAP];
};
void getData(songInfo Song[], int listSize, int charSize);
int main()
{
string fileName;
songInfo Song[CAP];
ifstream inFile;
cout << "What is the file location?: ";
cin >> fileName;
inFile.open(fileName.c_str());
if (inFile.fail())
{
cout << "Cannot open file " << fileName << endl;
exit(1);
}
getData(Song, CAP, MAXCHAR);
for (int i=0;i<CAP;i++)
{
cout << Song[i].title << " - "
<< Song[i].durMin << ":"
<< Song[i].durSec << endl;
}
cout << "Press any button to continue..." << endl;
cin.get(); cin.get();
return 0;
}
void getData(songInfo Song[], int listSize, int charSize)
{
for (int i = 0; i < listSize; i++)
{
cin.get(Song[i].title, charSize, ';');
cin.get(Song[i].durMin, charSize, ';');
cin.get(Song[i].durSec, charSize, '\n');
i++;
cin.ignore();
}
}
The program compiles correctly without incident, but the output is not what I want it to be. What should happen:
Test.cpp opens songs.txt
Read the first char array into Song[i].title, delimited by ';'
Read the second char into Song[i].durMin, delimited by ';'
Read the third char into Song[i].durSec, delimited by newline
After compiling the code and running it, I get this as my output:
~/project2Test> ./test
What is the file location?: songs.txt
The program then hangs here and I have to ctrl+C out
First, what am I doing wrong?
Second, how do I go about fixing what I screwed up?
Also, as a note for class rules, I am not allowed to use any strings except for the filename. Other than that, all words must be chars.
A debugger is definitely a good thing to use for a problem like this.
Your hanging problem is occurring because in your get_data function you are using cin.get instructing your program to get input from the standard input file. You intended to use the file you defined, "inFile" not the standard input cin.
As an aside it is not clear to me why you are incrementing i twice per iteration of the for loop.
Use inFile.get() instead of cin. You need to pass inFile to the function first.
Put a print statement in the for loop to see what is happening.. A future issue that might crop up is that if you are on a Windows machine and have \r\n line endings. Unix uses \n, Windows uses \r\n

Command Line Test Program -> Only producing first part

The assignment given in class was to test arguments that where provided.The code that wrote(added to this topic) works ( in the sense that it runs) , but it only produces the first word or set of words.
Code:
#include <fstream>
#include <iostream>
using namespace std;
int main ( int argc , char *argv[] )
{
if(argc > 1 )
{
cout << argv[1] << endl;
}
else
{
return -1;
}
ifstream infile(argv[1]);
if (infile.is_open())
{
string words;
while (infile >> words)
{
cout << words <<endl;
}
}
else
{
return -1;
}
infile.close();
}
The given line is :
"This is true" "This is fact"
The outcome it(code) produces is:
This is true
The outcome that I want is:
This is true , this is fact
Another Example:
The given line :
check if this thing works
Output using this code :
check
Wanted output:
check, if, this, thing, works
My question is if I am not adding something in my code that will produce the whole line. Also, I know that my code does not add "," to the output, but I want to worry about one issue at a time.
Some more information:
The file is read and if there is no arg then it does not produce anything, it also works if there is only one arg. he code stops working at more then one arg and quotes.
This line cout << argv[1] << endl; will print your first command line argument (after argument zero which is the application name) to the screen. Command line arguments wrapped in double quotes are treated as a single argument so for your first example argv[1] = This is true and for the second argv[1] = check. That's why you see what you see.
If you understand this you should be able to figure out how to make it print the whole thing. i.e. command line arguments > 1.

How to check program start parameters from Windows Console?

At the start of my program, it should get path to the input file and path to the output file from the console.
But if user give not required number of parameters or wrong parameters (with spaces for example, or without ".txt") it should give the user second chance to enter those parameters without exiting the program. Is it possible?
int main(int argc, char* argv[])
{ //and here should be something to check if the user entered parameters correctly
//(number and if they look like a path) and give a user another try if this is wrong
//(so that user enter them from console again)
string path_open(argv[1]);
strin path_out(argv[2]);
Yes it's possible, but... weird. If you are going to have your program ask for input, why not just put that in a loop until you get proper input? Ultimately, I'd do one or the other:
Get command line input (and, as #IInspectable suggests in the comments, if it's not valid, exit the program); OR
Have program ask for input recursively until the user gives valid input.
Input from command line:
int main(int argc, char* argv[])
{
// sanity check to see if the right amount of arguments were provided:
if (argc < 3)
return 1;
// process arguments:
if (!path_open(argv[1]))
return 1;
if (!path_out(argv[2]))
return 1;
}
bool path_open(const std::string& path)
{
// verify path is correct...
}
Program asks for input:
int main()
{
std::string inputPath, outputPath;
do
{
std::cout << "Insert input path: ";
std::getline(std::cin, inputPath);
std::cout << std::endl;
std::cout << "Insert output path ";
std::getline(std::cin, outputPath);
} while (!(path_open(inputPath) && path_out(outputPath)));
}
Of course you'd validate input separately in case they were entering a valid input path but invalid output path, but you get the gist.

Why does the program end when I enter a number?

I began programming on C++ some days ago and something is really getting me troubles:
whenever I enter the number, the program ends.
Code:
using namespace std;
int main()
{
int entry;
cout << "Write a number: ";
cin >> entry;
cout << entry;
cin.get();
return 0;
}
I need some help here so my programs could run right.
By right I mean to output the number after ending... but it just ends after I enter the number and press enter It does not print it.
UPDATE:
For the sake of the ones who didn't understood what I was meaning (sorry for my english)
Ok let me explain.
-So the program is suposed to get the values from the keyboard right.
-I enter a number let´s say is 6, ok now I press enter.
-Alright now the number is supposed to be output on the screen, but this doesn´t happen because the program closes too fast.
But this was solved actually, by adding a second cin.get(); or by adding a cin.ignore(); after each data input petition.
Here's a slightly improved version that might be closer to what you wanted:
#include <string>
#include <sstream>
#include <iostream>
int main()
{
int n;
std::string line;
while (true)
{
std::cout << "Please enter an integer: ";
if (!(std::getline(std::cin, line))) { return 1; /* error! */ }
std::istringstream iss(line);
if (iss >> n) { break; }
}
std::cout << "Thank you. You said: " << n
<< "\n\nPlease press Enter to quit.";
std::getline(std::cin, line);
}
The error condition in the getline is triggered when the input stream is closed or otherwise terminated before another line could be read (e.g. if you hit Ctrl-D on the console). The token extraction into n fails until you enter a valid integer, and the loop will continue looping until this happens.
All you need to do is consume the newline that is left over after reading the integer.
This happens in java as well.
using namespace std;
int main()
{
int entry;
cout << "Write a number: ";
cin >> entry;
cout << entry;
cin.get(); //Consume newline
cin.get();
return 0;
}
get() reads one and only one character from the stream, so it's perfectly normal that the program ends after you enter your number.
Have a look either at the std::basic_istream<>::getline() method or, easier, std::getline() which doesn't require a dynamic buffer.
If you need more information about basic IO in C++, you can read the following documentation : Basic Input/Output - C++
Update
Like stated in the comments, I missunderstood the question, I was initially thinking that only one digit was read into the variable.
After reading carefully again, I'm unable to understand what the problem is.
The reason for this is youre using
cin.get();
return 0;
at the end of the program , the cin.get() reads the number you entered then goes straight to return 0; thus ending the program.
to stop this you can add an extra cin.get(); before return 0;
or use
system("Pause");
before return 0; instead