-1

こんにちは、割り当てのために C でシェルを書いていますが、関数 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)));
4

1 に答える 1

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++;
    }
}

または、このようなもの。アイデアは、文字列バッファーの先頭から開始し、単語を見つけるたびに 1 つ追加して反復し、空白ができるまですべての文字を無視し、無視して単語のカウントを再開するというものです。 、文字列の最後に到達するまで (通常は '\n' であり、ユーザーが 512 文字を超えて入力した場合は '\0' である可能性があります)。

あなたがアイデアを持っていることを願っています。

于 2013-03-13T02:03:32.257 に答える