从指向字符数组的指针中提取输入
Extract inputs from a pointer to array of characters
我正在编写命令行实用程序,但找不到存储命令和参数的方法。 到目前为止,我有以下内容,但我遇到了分段错误:
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::string
和 std::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 输入数据。
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 如何从 std::atomic 中提取指针 T<T>?
- std::unordered_map::提取引用/指针失效
- 从指向结构数组的指针中提取元素
- 如何在将原始指针移动到基类构造函数之前从unique_ptr中提取原始指针
- C 仅使用指针从多维数组中提取特定列
- 提取操作员在使用来自其他类名的指针时超载
- 为什么将指针指向std ::设置的提取节点是未定义的行为
- 带有指针的重载插入/提取运算符
- STL/Boost 中的函子,从指针中提取值
- 从结构中提取指针参数
- 提取函数指针参数和返回类型
- 从指向字符数组的指针中提取输入
- 如何从Lua中提取C++对象指针
- R内部:从一个SEXP对象中提取函数指针
- c++提取指针的类型
- 从容器中提取指针的语法()
- 提取2个指针类型转换为(void*)
- 从转换运算符到函数指针提取返回类型和参数类型