运行main带参数的控制台应用程序方法

时间:2023-01-31 21:25:48

很多时候会遇到这种情况:在运行程序时要给main函数传递参数.在linux下这个很普遍,但是windows下这个不常见,大家习惯使用vs的Ctrl+F5的功能直接运行程序.然而,当要给main函数传递参数时,这个方法就行不通了,下面举例说明如何运行这类程序.

<C++ Primer>书上有这么一道例子:

10.3.9. “单词转换” map 对象.

要求如下本程序的输入是两个文件。第一个文件包括了若干单词对,每对的第一个单词将出现在输入的字符串中,而第二个单词则是用于输出。本质上,这个文件提供的是单词转换的集合——在遇到第一个单词时,应该将之替换为第二个单词。第二个文件则提供了需要转换的文本。如果单词转换文件的内容是:将这个文件命名为first.txt

'em       them
cuz       because
gratz    grateful
i           I

nah    no
pos    supposed
sez    said
tanx   thanks
wuz   was

而要转换的文本是:将这个文件命名为second.txt

nah i sez tanx cuz i wuz pos to
not cuz i wuz gratz
则程序将产生如下输出结果:
no I said thanks because I was supposed to
not because I was grateful

源代码如下:假如生成的可执行文件名为:Test _10_3.exe

  /*
* A program to transform words.
* Takes two arguments: The first is name of the word transformation file
* The second is name of the input to transform
*/
int main(int argc, char **argv)
{
// map to hold the word transformation pairs:
// key is the word to look for in the input; value is word to use in the output
map<string, string> trans_map;
string key, value;
if (argc != 3)
throw runtime_error("wrong number of arguments");
// open transformation file and check that open succeeded
ifstream map_file;
if (!open_file(map_file, argv[1]))
throw runtime_error("no transformation file");
// read the transformation map and build the map
while (map_file >> key >> value)
trans_map.insert(make_pair(key, value));
// ok, now we're ready to do the transformations
// open the input file and check that the open succeeded
ifstream input;
if (!open_file(input, argv[2]))
throw runtime_error("no input file");
string line; // hold each line from the input
// read the text to transform it a line at a time
while (getline(input, line)) {
istringstream stream(line); // read the line a word at a time
string word;
bool firstword = true; // controls whether a space is printed
while (stream >> word) {
// ok: the actual mapwork, this part is the heart of the program
map<string, string>::const_iterator map_it =
trans_map.find(word);
// if this word is in the transformation map
if (map_it != trans_map.end())
// replace it by the transformation value in the map
word = map_it->second;
if (firstword)
firstword = false;
else
cout << " "; // print space between words
cout << word;
}
cout << endl; // done with this line of input
}
return 0;
}

程序运行时需要待三个参数(argc=3),第一个生成的可执行程序名 Test _10_3.exe,第二个用来单词转换文件 first.txt,第三个要转换的文件 second.txt

则运行程序方法如图中所示:

运行main带参数的控制台应用程序方法