如何将字符串流读入 char *[40] / char ** 数组?

How do I read a stringstream into a char *[40] / char ** array?

我正在为实验室作业创建 UNIX shell。这部分涉及存储过去 10 个命令的历史记录,包括传递的参数。我将每个命令存储为 C++ 字符串,但程序中真正重要的部分,以及我在设计时没有输入的部分(例如 execve)专门使用 char * 和 char ** 数组。

我可以从历史记录中获取整个命令,然后很容易地读取要调用的程序,但是我很难读取一个参数数组,它是一个 char *[40] 数组。

下面是我编写的用于在测试字符串上模拟此行为的程序代码:

#include <sstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
   char *chars[40];
   string test = "Hi how are you";
   stringstream testStream;
   testStream << test;
   int i = 0;
   while (true)
   {
      string test_2;
      testStream >> test_2;
      if (testStream.fail())
      {
         break;
      };
      chars[i] = (char *)test_2.c_str();
      i++;
   }
   for (int i=0; i < 4; i++)
   {
      cout << chars[i];
   }
   cout << "\n";
}

我感觉这与声明为指针数组而不是多维数组的数组有关。我说得对吗?

这一行:

chars[i] = (char *)test_2.c_str();

离开 chars[i] 'dangling' 当你返回循环或从终点掉下来。这是因为 test_2.c_str() 仅在 test_2 在范围内时有效。

你最好这样做:

#include <sstream>
#include <iostream>
#include <string>
#include <vector>
#include <memory>

int main()
{
   std::vector <std::string> args;
   std::string test = "Hi how are you";
   std::stringstream testStream;
   testStream << test;
   int i = 0;

   while (true)
   {
      std::string test_2;
      testStream >> test_2;
      if (testStream.fail())
         break;
      args.push_back (test_2);
      i++;
   }

    auto char_args = std::make_unique <const char * []> (i);
    for (int j = 0; j < i; ++j)
        char_args [j] = args [j].c_str ();

    for (int j = 0; j < i; ++j)
        std::cout << char_args [j] << "\n";
}

现在,当您构建和使用 char_args 时,您的字符串向量仍保留在范围内。

Live demo