【发布时间】:2014-10-26 08:30:30
【问题描述】:
我正在尝试从命令行参数打开一个文件。
我已经调试了我的程序:
当我打印文件的值时,它给出的值是。
当我打印 argv 的值时,它给出的值 (char **) 0x7ffffffffe4e0。
当我打印 argv[1] 的值时,它给出的值是 0x0。
该函数不会打开我的文件。不知道为什么?
我试过了:
if (file.is_open()) 也是同样的问题。
在我的主要功能中,我通过了:
buildBST(&argv[1]);
BSTTreeData buildBST (char *argv[]){
vector <string> allwords;
BSTTreeData Data;
BinarySearchTree<string> Tree;
ifstream file (argv[1]);
char token;
string listofchars = "";
string input;
int distinct = 0;
int line = 1;
if (file){
//if the file opens
while (getline(file, input)) //gets every line in the file
{
for (int i = 0; i < input.size(); ++i) //gets all the contents in the line
{
token = input[i]; //each character become a 'token'
if (isalpha(token))
{
//if the character is an alphabetical character
listofchars += token; //append character to a string
if (Contains(allwords, listofchars) == false)
{
//if the current word has not already been added to vector of words
//increment the distinct word count
distinct += 1;
Tree.insert(listofchars); //creates the BST
allwords.push_back(listofchars);
//add current word to vector of all the words
}
else
line++; //increments the line number
}
else
line++; //increments the line number
}
listofchars = ""; //creates empty character string
}
}
file.close(); //closes file
Data.BST = Tree;
Data.linenumber = line;
Data.distinctwords = distinct;
Data.words = allwords;
return Data;
}
【问题讨论】:
-
如果
argv[1]是NULL,那么问题在于您没有将文件名作为第一个参数传递。你是如何运行程序的? -
我使用 'g++ -g -std=c++11 myfile.cpp' 编译并执行 './a.out test.txt'
-
等等,你将
&argv[1]传递给buildBST,这意味着buildBST中的argv参数现在指向第一个参数。这意味着argv[1]内buildBST指的是第二个参数,而不是第一个! (请记住,C 中的索引是从零开始的。) -
好吧,这是有道理的。那么你的意思是我应该将 argv[0] 传递给 buildBST?并更改'ifstream file (argv[0]);'?
-
arg[0]通常包含应用程序的路径,而不是传递给它的第一个参数(即/bin/appname)。
标签: c++ text-files command-line-arguments ifstream