0

I have made some code and need to make the length of an array the same as a user input:

#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;
}

I don't really know what I could possibly do, I have no ideas. I was using a compiler that just side steps this problem, so I didn't realize it until I submitted this code to codeforces.com, in which I got these errors:

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

Also I don't think the last error has anything to do with it, if you could help with that to that would be awesome! Thankful for any help!

Piggy
  • 67
  • 7

1 Answers1

1

It's mostly duplicated, to resolve the error, it's easy to fix it with std::vector

Since the function abrev doesn't change the argument, it's better to use a const reference.

#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;
}
prehistoricpenguin
  • 6,130
  • 3
  • 25
  • 42