您好我在C中编写了一个用于赋值的shell,我不知道如何计算并在函数count()中返回缓冲区内的参数数量。这就是我到目前为止所拥有的。 提前谢谢。
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
int count(char* buffer)
{
int count=0;
//COUNT ARGS WITHIN BUFFER HERE
return count;
}
int main(int argc, char **argv)
{
//buffer is to hold the commands that the user will type in
char buffer[512];
// /bin/program_name is the arguments to pass to execv
//if we want to run ls, "/bin/ls" is required to be passed to execv()
char* path = "/bin/";
while(1)
{
//print the prompt
printf("myShell>");
//get input
fgets(buffer, 512, stdin);
//fork!
int pid = fork();
//Error checking to see if fork works
//If pid !=0 then it's the parent
if(pid!=0)
{
wait(NULL);
}
else
{
int no_of_args = count(buffer);
//we plus one so that we can make it NULl
char** array_of_strings = malloc((sizeof(char*)*(no_of_args+1)));
答案 0 :(得分:1)
我认为你想要计算的是在char *缓冲区中用空格分隔的单词数。你可以用代码来做到这一点:
int i=0;
bool lastwasblank = false;
while (buffer[i] == ' ') i++; //For us to start in the first nonblank char
while (buffer[i] != '\0' && buffer[i] != '\n') {
if (buffer[i] != ' ') {
count++;
while(buffer[i] != ' ') i++;
}
else {
while(buffer[i] == ' ') i++;
}
}
或类似的东西。这个想法是你从字符串缓冲区的开头开始,然后你遍历它,每次找到一个单词时添加一个,然后你忽略每个字符,直到有空格,你忽略并开始再次计算单词,直到你到达字符串的末尾(通常可以是&#39; \ n&n;正常,或者如果用户键入超过512个字符,则为&#39; \ 0;)< / p>
希望你有这个主意。