Download pdf - C++ Command Line Inputs

Transcript
Page 1: C++ Command Line Inputs

This is how you would write a simple program in C++ that takes inputs from the command line.The argc variable refers to the the number of arguments supplied.The args array contains all the arguments supplied, in the form of strings.

This is the sample program.#include <iostream>#include <fstream>#include <string>#include <cstring>

using namespace std;

int wordCounter(string textline){int count = 0;for(int i = 0; i < textline.length(); i++){

if(textline[i] == ' '){count += 1;

}}return count+1;

}

int main(int argcount, char *args[]){string stuff, filename;ifstream wordlist(args[1]);if(wordlist.good()) {

int count = 0;while(getline(wordlist, stuff)) {

count += wordCounter(stuff);}cout << "Number of words in this document: " << count <<

endl;}else{

cout << "The file you entered does not exist." << endl;}

}

This program simply counts the number of words in a given document.However, it does not do "real" counting.It only looks for strings that are separated, or delimited by spaces, or the spacecharacter.

Recommended