【发布时间】:2021-05-31 17:36:45
【问题描述】:
我在 C++ 中对反向布尔值有一些奇怪的问题。 :')
我想检查传递给 main 方法的参数是否不是“file.txt”。如果不是,我想创建一个名称作为主要参数的新文件,并在那里写入随机数据行。否则我想从“file.txt”中读取数据。
一切都如我所愿,但是当我输入
g++ sourcefile.cpp header.h 在终端中,然后
./a.out file.txt
程序将这些随机数据输入到“file.txt”中,而不是从中读取。
另一方面,当我输入:
./a.out someRandomData.txt 它正在从“file.txt”中读取。有什么想法吗?
int main(int argc, char* argv[]) {
if(argv[1] != "file.txt"){
fileWithRandomData(argv[1]);
}
else{
std::vector<std::string> row;
std::string line, word, temp;
std::ifstream MyReadFile(argv[1]);
(...)
这是我的 fileWithRandomData 函数的示例:
void fileWithRandomData(string name){
srand(time(NULL));
std::ofstream MyFile(name);
int metalsNumber = rand() % 5000 + 1; //first line -> number of available metals.
(...)
【问题讨论】:
-
argv[1] != "file.txt"永远不会是假的。 -
您使用的是 C++?请直接将参数转换为 std::string_view 或 std::string,并始终确保您确实传递了正在检查的参数(例如,不带参数调用将超出范围访问)。更好的是,使用一个处理命令行接口的好库:)
标签: c++ string-comparison c-strings boolean-logic