c - C程序的奇怪输出
问题描述
我的任务是创建一个从 CL 中提取输入并与它们一起工作的程序
它应该执行以下操作
输入 ./name Test + Best + Rest 输出 TestBestRest
输入 ./name 600 + 500 - 100 输出 1000
单词只会连接到字符串,但数字必须能够添加或减去。在混合字符串中,所有内容都被视为字符串而不是整数。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main(int argc, char *argv[])
{
char arr1[15][25]={'\0'};
int nums=0;
int temp;
char tempstring[15]={'\0'};
char symbol[15]={'\0'};
int tempnum=0;
int endnum=0;
char strcat[100]={'\0'};
printf("This program only recognizes 10 command line entries\n");
for(int indx=1;indx<argc;indx+=1)
{
char *input = argv[indx];
// if(isalnum(input[indx]))
strncpy(tempstring,argv[indx],14);
if (indx>1)
strncpy(symbol,argv[indx-1],14);
printf("index is %d\n",indx);
printf("Tempstring is %s\n\n",tempstring);
tempnum=atoi(tempstring);
printf("Tempnum is %d\n",tempnum);
if(tempnum!=0)
{
printf("inside %d\n", indx);
printf("Temp num %d and End num is %d\n", tempnum,endnum);
// printf("is num\n");
printf("Tempstring is %s\n\n",tempstring);
printf("Tempnum is %d\n",tempnum);
printf("symbol is %c\n\n",symbol[0]);
if (symbol[0]==45)
{
endnum=endnum-tempnum;
printf("minus\n");
}
else if(symbol[0]==43)
{
printf("plus\n");
endnum=endnum+tempnum;
}else if (indx==1)
{
printf("no sym\n");
endnum=endnum+tempnum;
}
}
if (isalpha(input[indx])!=0)
{
printf("argv[%d] = %s\n",indx, tempstring);
//strncpy(arr1[indx],argv[indx],10);
if (tempstring[0]!=43)
strncat(strcat,tempstring,14);
}
}
printf("End number %d\n",endnum);
printf("Concatenated %s\n", strcat);
return 0;
}
代码按要求执行(我很抱歉检查 printfs 的错误),但有一个例外
如果输入 ./name Test + Rest + Best + 600 则输出 TestRest600。
这就是 printfs 的代码结果
─╼ $./a6p1 Test + Rest + Best + 600
This program only recognizes 10 command line entries
index is 1
Tempstring is Test
Tempnum is 0
argv[1] = Test
index is 2
Tempstring is +
Tempnum is 0
argv[2] = +
index is 3
Tempstring is Rest
Tempnum is 0
argv[3] = Rest
index is 4
Tempstring is +
Tempnum is 0
argv[4] = +
index is 5
Tempstring is Best
Tempnum is 0
index is 6
Tempstring is +
Tempnum is 0
argv[6] = +
index is 7
Tempstring is 600
Tempnum is 600
inside 7
Temp num 600 and End num is 0
Tempstring is 600
Tempnum is 600
symbol is +
plus
argv[7] = 600
End number 600
Concatenated TestRest600
任何帮助都会受到欢迎,我知道它有一些垃圾代码,我需要在第二次通过时清理它们,但我希望先解决这个问题。
解决方案
你的问题是:
if (isalpha(input[indx])!=0)
该变量indx
用于索引程序的参数,在这里您使用它来索引参数中的字符,这是一个非常糟糕的主意。因为参数Best
索引等于5
并且访问“Best”[5] 会给你一个'\0',它是一个字符串终止符,而不是一个字母,这就是为什么Best
不连接的原因。
您可能应该改用它:
if (isalpha(input[0])!=0)
推荐阅读
- python - 'Client' object has no attribute 'send_message' error
- user-experience - 可以改善 dbeaver UX/减少所需的点击次数吗?
- vue.js - Vuetify 2.4.2 打破了 Gridsome 0.7.23 构建
- python - 将 Panel 和 Altair 交互式图表保存为 HTML
- vba - 在上标单词前插入 ^{
- ansible - 如何插入一个新行,然后在 Ansible 中附加到它?
- pine-script - 在时间范围内绘制框/矩形
- android - 使用 M1 Mac 构建 APK 时 Flutter 视频无法播放
- api - 将跟踪号硬编码到 URL 中
- python - 为什么我们像这样在 Django 自定义中间件中使用第一类函数?