从指向字符数组的指针中提取输入

Extract inputs from a pointer to array of characters

本文关键字:指针 提取 输入 数组 字符      更新时间:2023-10-16

我正在编写命令行实用程序,但找不到存储命令和参数的方法。 到目前为止,我有以下内容,但我遇到了分段错误:

int main(void)
{
    char *command;
    char *args[MAX_LINE/2 + 1]; 
    int should_run = 1;
    do{
         cout << "cmd> ";
         int counter = 0;
         while(cin >> command) {
             strcpy(args[counter],command);
             counter++;
         }
        cout << args[0] << "n";
    }  
}

您会收到分段错误,因为:

cin >> command

尝试写入未初始化的内存。由于这是C++,您应该执行以下操作:

std::string command;

而不是:

char * command;

同样对于args.然后你可以做args[counter] = command而不是使用 strcpy() .对于加分,请执行std::vector<std::string> args而不是使用数组,args.push_back(command)而不是args[counter] = command

例如:

#include <iostream>
#include <vector>
#include <string>
int main() {
    std::string command;
    std::vector<std::string> args;
    std::cout << "cmd> ";
    while( std::cin >> command ) {
        args.push_back(command);
    }
    int i = 0;
    for ( auto a : args ) {
        std::cout << "Arg " << i++ << " is " << a << std::endl;
    }
    return 0;
}

输出:

paul@local:~/src/cpp/scratch$ ./args
cmd> test this command
Arg 0 is test
Arg 1 is this
Arg 2 is command
paul@local:~/src/cpp/scratch$

一个常见的误解是char *在 C 或 C++ 中扮演特殊角色,主要是出于合法的动机:

char const * foo = "String";

事实上,char *仍然只是一个指向 char 的指针,因此您需要先分配内存,然后才能为其分配字符串文字。您在代码中遇到此问题两次:

char * command;
std::cin >> command;

char * arr[N];
std::strcpy(arr[k], command);

在C++中,您应该为此使用 std::stringstd::vector<std::string> 等容器。如果您坚持使用 char 数组,则可以确定静态最大长度:

char command[MAX_LENGTH];
char args[N][MAX_LENGTH];

或动态使用new[]

char * command = new char[MAX_LENGTH];
char * args[N];
for(unsigned k = 0; k < N; ++k) args[k] = new char[MAX_LENGTH];

但是你也必须记住释放那段记忆:

delete[] command;
for(unsigned k = 0; k < N; ++k) delete[] args[k];
因此,除非您有充分的理由

不这样做,否则您应该更喜欢自动存储持续时间,因为您也应该有充分的理由不使用容器。

此语句

while(cin >> command)

无效。首先,变量命令未初始化,其次,您必须分配流 cin 可以放置数据的内存。使用字符数组(静态或动态分配)或使用类 std::string 输入数据。