【问题标题】:Dynamically input 2d character array in C++在 C++ 中动态输入二维字符数组
【发布时间】:2014-10-26 00:51:50
【问题描述】:

我正在尝试使用字符数组输入一个单词序列。我不想使用 STL 中的字符串。我哪里错了?

int n;
cout<<"Enter the number of words:";
cin>>n;
char **s = new char*[n];
for(int i=0;i<n;i++)
{
  char *s = new char[10];
  cin>>s[i];

}

【问题讨论】:

  • 使用std::vector而不是自己管理内存会让您受益匪浅。像std::vector&lt;std::vector&lt;char&gt;&gt;(n, std::vector&lt;char&gt;(10)) 这样的东西。如果您存储字符串std::vector&lt;std::vector&lt;std::string&gt;&gt;(n)
  • I don't want to use string from STL 有什么原因吗?
  • 只是因为我想了解它如何与 char 一起使用。
  • 我也认为你应该使用 Vector。
  • @lostboy_19 Just beacuse I want to learn how it would work with char 因此,如果您想学习,请查看 SO 和其他网站上数千个正确编码的动态数组类的示例。无需将不工作的代码放在一起,然后想知道下一步该做什么。

标签: c++ arrays string dynamic


【解决方案1】:

看看 char *s = new... 正在初始化什么。与 s[i] 所指的位置不同。

实际上它是错误的,原因有两个——一是char *s是for循环范围内的新声明,二是它没有被i索引。

我认为你需要 s[i] = new char[10] 没有 char 声明,因为 s 是一个双指针,所以 s[i] 已经是一个指针。

为这么多的编辑道歉,为时已晚....

【讨论】:

    【解决方案2】:

    使用

    char ch[n+1];
    for(int i = 0;i<n;i++)
    `cin>>ch[i];
    ch[n] = '\0';
    cout<<ch<<endl;
    

    【讨论】:

      【解决方案3】:

      通过将 cin 用于 char 数组,您很容易遇到缓冲区溢出问题,正如您在 https://stackoverflow.com/a/15642881/194717 上看到的那样

      您可以执行以下代码之类的操作,但请注意,执行此任务的一种简洁方法是使用 vectorstring

      #include "stdafx.h"
      #include <iostream>
      #include <vector>
      #include <string>
      using namespace std;
      
      int _tmain(int argc, _TCHAR* argv[])
      {
          int n;
          cout << "Enter the number of words:";
          cin >> n;
      
          //vector<string> list(n);
          vector<char[100]> list(n);
      
          // Request from user the words
          for (int i = 0; i < n; i++)
              cin >> list[i];
      
          // Display the list
          //for each (string word in list)
          //  cout << word << endl;
          for (int i = 0; i < n; i++)
              cout << list[i] << endl;
      
          return 0;
      }
      

      【讨论】:

        猜你喜欢
        • 2018-05-17
        • 2014-11-13
        • 2021-10-08
        • 1970-01-01
        • 2017-03-11
        • 2018-02-28
        • 2013-01-10
        • 1970-01-01
        相关资源
        最近更新 更多