gpt4 book ai didi

检查命令行参数是否正确 - C 编程

转载 作者:行者123 更新时间:2023-11-30 18:53:39 25 4
gpt4 key购买 nike

我正在尝试编写代码,表示如果有命令行输入,则执行某些操作,如果不执行其他操作。

int main(int argc, char *argv[])
{
int lowerBound, upperBound, i, count = 0;
float val;
char c;

if(argc = 2)
{
lowerBound = argv[1];
printf("Lower bound = %d", lowerBound);

item * curr, * head;
head = NULL;

do
{
printf("Enter a number: ");
scanf("%f", &val);
curr = (item *)malloc(sizeof(item));

if(val >= lowerBound)
{
curr->num = val;
curr->next = head;
head = curr;
count++;
}

getchar();
printf("Want to enter another number (y/n): ");
scanf("%c", &c);
} while( c != 'n' && c != 'N' );

curr = head;

float largest = findLargest(curr);
float lowest = findSmallest(curr);
float mean = findMean(curr, count);
int ValuesAboveMean = valuesAboveMean(curr, mean);
int ValuesBelowOrAtMean = valuesBelowOrAtMean(curr, mean);
float median = findMedian(curr, count);
show(count, lowest, largest, mean, median, ValuesAboveMean, ValuesBelowOrAtMean);
}
else if(argc = 3)
{
lowerBound = argv[1];
upperBound = argv[2];
printf("Lower bound = %d", lowerBound);
printf("Upper bound = %d", upperBound);
item * curr, * head;
head = NULL;

do
{
printf("Enter a number: ");
scanf("%f", &val);
curr = (item *)malloc(sizeof(item));

if(val >= lowerBound && val <= upperBound)
{
curr->num = val;
curr->next = head;
head = curr;
count++;
}

getchar();
printf("Want to enter another number (y/n): ");
scanf("%c", &c);
} while( c != 'n' && c != 'N' );

curr = head;

float largest = findLargest(curr);
float lowest = findSmallest(curr);
float mean = findMean(curr, count);
int ValuesAboveMean = valuesAboveMean(curr, mean);
int ValuesBelowOrAtMean = valuesBelowOrAtMean(curr, mean);
float median = findMedian(curr, count);
show(count, lowest, largest, mean, median, ValuesAboveMean, ValuesBelowOrAtMean);
}
else if(argc = 1 or argc = 0 or argc = NULL)
{
item * curr, * head;
head = NULL;

do
{
printf("Enter a number: ");
scanf("%f", &val);
curr = (item *)malloc(sizeof(item));

curr->num = val;
curr->next = head;
head = curr;
count++;

getchar();
printf("Want to enter another number (y/n): ");
scanf("%c", &c);
} while( c != 'n' && c != 'N' );

curr = head;

float largest = findLargest(curr);
float lowest = findSmallest(curr);
float mean = findMean(curr, count);
int ValuesAboveMean = valuesAboveMean(curr, mean);
int ValuesBelowOrAtMean = valuesBelowOrAtMean(curr, mean);
float median = findMedian(curr, count);
show(count, lowest, largest, mean, median, ValuesAboveMean, ValuesBelowOrAtMean);
}

目前由于某种原因,它会忽略 if 语句中的内容并运行 if 中的内容。例如,即使我没有命令行参数,它仍然想运行第一个 if where arg = 2。

我做错了什么以及如何解决它?

最佳答案

你需要这样做 if(argc == 2)

(而不是 if(argc = 2),它将 2 分配给 argc 并且始终为 true)。我从来不喜欢 C 定义 = 与 == 的方式。有些编译器会为此产生警告。

关于检查命令行参数是否正确 - C 编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32447162/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com