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

问题描述 投票:0回答:1

我正在为实验分配创建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";
}

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

c++ arrays string stringstream
1个回答
0
投票

此行:

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

chars[i]“悬垂”,当您绕圈返回或从末端掉下来时。这是因为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";
}

Live demo

© www.soinside.com 2019 - 2024. All rights reserved.