当我加载少于 5 个字符时,没问题。但是,如果我加载超过五个字符,我的程序就会崩溃。 在那之前我该如何保护?
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
char tab[5];
int tab2[5];
char *wsk = tab;
int i = 0;
cin >> tab;
while (true) {
cin >> tab2[i];
if (tab2[i] == 0) break;
i++;
}
i = 0;
while (true) {
if (tab2[i] ==0) break;
wsk += tab2[i];
cout << *wsk;
i++;
}
return 0;
}
最佳答案
您不想将其限制为 5 个。
您真正想要的是确保读取有效且永不崩溃。
你不想在 5 个字符处停止阅读的原因是,如果用户输入超过 5 个字符,你会在他们输入的中间停止阅读,你现在必须编写代码来找到这个输入的结尾然后继续。编写代码来修复输入流很困难。而是进行输入验证(用户可能输入了废话并且您可以生成错误消息)但您将在正确的位置继续阅读下一个输入操作。
char tab[5];
cin >> tab; // Fails if you read more than 4 input characters
// (because it will add '\0' on the end)
为什么不使用自扩展目标结构。
std::string tab;
std::cin >> tab; // Read one word whatever the size.
但是数组呢。
不再困难。在这里你想要一个重新调整大小的数组。猜猜我们有什么 std::vector
int tab2[5];
while (true) {
cin >> tab2[i]; // Fails on the 6 number you input.
// STUFF
}
循环可以这样写:
std::vector<int> tab2;
while (true) {
int val;
cin >> val;
tab2.push_back(val);
// STUFF
}
关于C++ 如何从标准输入加载到最多 5 个字母数字字符的字符数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19620277/