gpt4 book ai didi

带空格的字符数组输入

转载 作者:行者123 更新时间:2023-11-30 17:08:58 24 4
gpt4 key购买 nike

如果我给 char *w="ls -l"提供硬代码值,我的程序工作正常,但我试图获取用户不工作的输入形式帮助我的代码::使用输入错误我不明白 fgets 的概念,使用 fgets 它给 execv 提供了 garbig 值

#include<stdio.h>
#include<sys/wait.h>
#include<stdbool.h>

void func(char **arr, char *w)
{
int i = 0, j = 0, k = 0;

char temp[100];

for (i = 0; i < 100; i++)
{
if (w[i] == '')
{
arr[k] = temp;
arr[k+1] = NULL;
break;
}
if (w[i] == ' ')
{
arr[k] = temp;
k++;
j = 0;
}
else
{
temp[j] = w[i];
j++;
}

}
}
int main()
{
char *n = "/bin/ls";
char *arr[10] = {''};
char p[100] = {''};
char *w = "ls -l";
int i = 0;
//printf("bilal-hassan-qadri $ >>");
//fgets(p, 100, stdin);
arr[2] = NULL;
bool found = false;
for (i = 0; i < sizeof(w); i++)
{
if (w[i] == ' ')
{
found=true;
func(arr,w);
break;
}
}
if (!found)
arr[0] = w;
int status;
int id = fork();
if (id == 0)
{
if (execv(n,arr) < 0)
{
printf("invalid commandn");
}
else
{
printf("ninvalid command");
}
}
else
{
wait(&status);
}
}

最佳答案

  • 在函数func中,您必须将字符串复制到arr的元素中而不是仅仅传递 temp 的地址,它会在离开函数时消失。如果您的系统支持,您可以使用 strdup 代替 copy_string
  • 在复制之前,您必须在 temp 中终止该字符串。
  • 空字符串常量'' 似乎无效。你不应该使用它。
  • fgets 存储换行符 \n(如果存在)。检查是否存在,如果不需要则将其删除。

固定代码:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/wait.h>
#include<stdbool.h>

char *copy_string(const char *str) {
char *s = malloc(strlen(str) + 1);
if (s) strcpy(s, str); else {perror("malloc"); exit(1);}
return s;
}

void func(char **arr, char *w)
{
int i = 0, j = 0, k = 0;

char temp[100];

for (i = 0; i < 100; i++)
{
if (w[i] == '\0' || w[i] == '\n')
{
temp[j] = '\0';
arr[k] = copy_string(temp);
arr[k+1] = NULL;
break;
}
if (w[i] == ' ')
{
temp[j] = '\0';
arr[k] = copy_string(temp);
k++;
j = 0;
}
else
{
temp[j] = w[i];
j++;
}

}
}
int main(void)
{
char *n = "/bin/ls";
char *arr[10] = {NULL};
char p[100] = {0};
char *w = "ls -l";
int i = 0;
//printf("bilal-hassan-qadri $ >>");
fgets(p, 100, stdin);
w = p;
arr[2] = NULL;
bool found = false;
for (i = 0; w[i] != '\0'; i++)
{
if (w[i] == ' ')
{
found=true;
func(arr,w);
break;
}
}
if (!found)
arr[0] = w;
int status;
int id = fork();
if (id == 0)
{
if (execv(n,arr) < 0)
{
printf("invalid commandn");
}
else
{
printf("ninvalid command");
}
}
else
{
wait(&status);
for (i = 0; arr[i] != NULL; i++) free(arr[i]);
}
return 0;
}

关于带空格的字符数组输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33456723/

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