首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我如何避免使用VLA?

我如何避免使用VLA?
EN

Stack Overflow用户
提问于 2021-07-14 10:06:04
回答 1查看 57关注 0票数 0

我编写了一些代码,需要使数组的长度与用户输入的长度相同:

代码语言:javascript
复制
#include <iostream>
#include <string>
using namespace std;

void abrev(string word) {
    int lastChar = word.length();

    if (lastChar > 10) {
        cout << word[0];
        cout << lastChar - 2;
        cout << word[lastChar - 1] << endl;
    } else {
        cout << word << endl;
    }
}
int main() {
    int n;

    cin >> n;


    string words[n];

    for (int i = 0; i <= n - 1; i++) {
        cin >> words[i];
    }


    for (int i = 0; i <= n - 1; i++) {
        abrev(words[i]);
    }

    return 0;
}

我真的不知道我能做什么,我没有想法。我使用的compiler只是避开了这个问题,所以直到我向codeforces.com提交了这段代码,我才意识到这一点,在这个代码中我得到了以下错误:

代码语言:javascript
复制
Can't compile file:
program.cpp
program.cpp(20): error C2131: expression did not evaluate to a constant
program.cpp(20): note: failure was caused by a read of a variable outside its lifetime
program.cpp(20): note: see usage of 'n'
program.cpp(23): warning C4552: '>>': operator has no effect; expected operator with side-effect

另外,我不认为最后的错误与它有任何关系,如果你能帮助它,那就太棒了!感谢您的帮助!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-07-14 11:58:02

它大部分是重复的,为了解决这个错误,可以很容易地用std::vector修复它

由于函数abrev不会更改参数,因此最好使用常量引用。

代码语言:javascript
复制
#include <iostream>
#include <string>
#include <vector>
using namespace std;

void abrev(const string& word) {
  int lastChar = word.length();

  if (lastChar > 10) {
    cout << word[0];
    cout << lastChar - 2;
    cout << word[lastChar - 1] << endl;
  } else {
    cout << word << endl;
  }
}
int main() {
  int n;

  cin >> n;

  std::vector<std::string> words(n);

  for (int i = 0; i <= n - 1; i++) {
    cin >> words[i];
  }

  for (int i = 0; i <= n - 1; i++) {
    abrev(words[i]);
  }

  return 0;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68371168

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档