我编写了一些代码,需要使数组的长度与用户输入的长度相同:
#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提交了这段代码,我才意识到这一点,在这个代码中我得到了以下错误:
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另外,我不认为最后的错误与它有任何关系,如果你能帮助它,那就太棒了!感谢您的帮助!
发布于 2021-07-14 11:58:02
它大部分是重复的,为了解决这个错误,可以很容易地用std::vector修复它
由于函数abrev不会更改参数,因此最好使用常量引用。
#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;
}https://stackoverflow.com/questions/68371168
复制相似问题