【问题标题】:How to make user input declare the size of string array?如何让用户输入声明字符串数组的大小?
【发布时间】:2015-02-03 20:48:46
【问题描述】:

类似

ifstream myfile ("example.txt");
        if (myfile.is_open())
        {
            while ( getline (myfile,line) )
            {
                nr++; //how many lines in a text file
            }
        }

string y[nr] = {};

仅当我指定像 y[10] 这样的实际数字时才有效。

【问题讨论】:

标签: c++ arrays string


【解决方案1】:

除非您使用不可移植的编译器扩展,否则您不能声明大小未知的数组。完成此操作的标准方法是使用vector

int x;
cout << "Size of your array: ";
cin >> x;
vector<string> y(x);

【讨论】:

  • ISO C99 中允许使用可变长度自动数组。作为扩展,GCC 接受可变长度数组作为结构或联合的成员。请参阅 GCC 的 6.19 Arrays of Variable Length
  • @jww 感谢您提及这一点。由于它被标记为 c++,我不想提及 C99。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多