【问题标题】:How do I read a stringstream into a char *[40] / char ** array?如何将字符串流读入 char *[40] / char ** 数组?
【发布时间】:2020-05-11 00:14:38
【问题描述】:

我正在为实验室任务创建一个 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】:

这一行:

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

【讨论】:

    猜你喜欢
    • 2019-04-09
    • 2011-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-22
    • 2019-08-04
    • 2011-02-07
    • 2021-12-20
    相关资源
    最近更新 更多