首先,您不能const
对 M 和 N 使用限定符,因为您将更改它们的值:
int N = 7;
int M = 8;//N is number of lines, M number of values
其次,您不需要检查(argv[0] != NULL) && (argv[1] != NULL)
,只需检查argc
(argument count) 是否大于或等于 3:
if(argc >= 3)
然后你需要把它转换成整数。如果您不想使用atoi
,并且如果您没有 C++11 编译器,您应该使用 C++stringstream
或 Cstrtol
stringstream ss;
int temp;
ss << argv[1]; // Put string into stringstream
ss >> temp; // Get integer from stringstream
// Check for the error:
if(!ss.fail())
{
M = temp;
}
// Repeat
ss.clear(); // Clear the current content!
ss << argv[2]; // Put string into stringstream
ss >> temp; // Get integer from stringstream
// Check for the error:
if(!ss.fail())
{
N = temp;
}
因此,整个代码将如下所示:
#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <sstream>
using namespace std;
int N = 7;
int M = 8;//N is number of lines, M number of values
//--------------
//-----Main-----
//--------------
int main(int argc, char* argv[])
{
if(argc >= 3)
{
stringstream ss;
int temp;
ss << argv[1]; // Put char into stringstream
ss >> temp; // Get integer from stringstream
// Check for the error:
if(!ss.fail())
{
M = temp;
}
// Repeat
// empty
ss.clear();
ss << argv[2]; // Put char into stringstream
ss >> temp; // Get integer from stringstream
// Check for the error:
if(!ss.fail())
{
N = temp;
}
cout << M << " " << N;
}
else
{
cout << "Invalid or no command line arguments found. Defaulting to N=7 M=8.\n\n" <<
endl;
}
//Blah blah blah code here
return 0;
}
此外,C 头文件包含c
前缀,而不是.h
后缀(<cstdio>
而不是<stdio.h>
)