如何在c中重新初始化char *变量

时间:2015-02-20 06:56:49

标签: c++ string pointers char

我正在使用c ++编写一个简单的shell。这是我的代码。它只能在一轮中正常工作,并且在while(1)循环的第二轮后停止工作。我实际上找到了原因,我的char *command变量将继续增长。例如,第一轮我在ls中键入,然后我的命令是" ls"。然后我在第二轮中键入的内容将添加到ls,所以如果我再次输入ls,那么我的命令变量将是lsls。所以它阻止我的shell正常工作。所以我想知道有没有办法重新初始化我的命令或删除我的命令的内容?

#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
using namespace std;

int main(){
int i=0;
char c;
char *command;
while (1){
        cout<< "#?: -> ";
        while (( c = getchar()) != '\n'){
        command[i++] = c;}


        if (strcmp(command, "exit") == 0){
                break;
        }
        if ( strcmp(command, "date")==0){
                system("date");
        }
        else if ( strcmp(command, "vim")==0){
                system("vim");
        }
        else if ( strcmp(command,"top")==0){
                system("top");
        }
        else if ( strcmp(command,"ps")==0){
                system("ps");
        }
        else if ( strcmp(command,"ls")==0){
                system("ls");
        }
         else if ( strcmp(command,"man")==0){
                system("man");
        }
        for (int j=0;j<100;j++){
        command[j]='/0';
        }
        cout<<command;

        //cin>>command;
}

return 0;
}

1 个答案:

答案 0 :(得分:1)

在while循环的开头添加i=0;

char *command= new char[100];
while (1){
        i=0;
        cout<< "#?: -> ";
        while (( c = getchar()) != '\n'){
        command[i++] = c;}

当您进入第二轮时,i具有上一轮的值,这会导致您的错误。因此,只需在while循环中将i初始化为零。您也没有给command一个地址,因为您尝试的任何地方都会导致未定义的行为。

这里也有错误

command[j]='/0';

应该是

command[j]='\0';

空字符为\0而不是/0