C++ 如何从标准输入加载到最多 5 个字母数字字符的字符数组
C++ How to load from the standard input to an array of chars at most 5 alphanumeric characters?
当我加载少于 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 ' ' 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
}
而不是:
while (true)
放:
while (i < 5)
对于 C 样式的数组,您必须将输入流的宽度设置为分配给缓冲区的字符数,否则您可能会写入数组末尾并导致缓冲区溢出。这通常使用ios_base::width
完成:
std::cin.width(5);
std::cin >> buffer;
您也可以使用机械手std::setw
:
std::cin >> std::setw(5) >> buffer;
它们都将流的最大宽度设置为 5 个字符。宽度将在第一次输入操作后重置为其默认值。
您的循环条件应该是
while(i < 5)
此外,for 循环将非常适合
for(int i = 0; i < 5; i++) {
// body
}
您可以使用 STL 的算法部分来绑定读取。例如:
int main(){
char c[5];
auto newEnd = std::copy_n(std::istream_iterator<char>(std::cin), 5, std::begin(c));
// if newEnd != c + 5 then it failed to read 5 characters
}
标准输入是流。你无法决定里面有什么。你所能做的就是从中读取并查看你得到了什么 - 要么你得到一些数据,要么你了解到流已经结束。
如果你真的只想读取五个字节,你可以使用std::cin.read(tab, 5)
;然后你必须调用std::cin.gcount()
来查看实际读取了多少字节,并且只消耗尽可能多的字节。
或者,您可以使用 C++ 的动态容器并使用 std::getline(std::cin, line)
在std::string line
中读取尽可能多的数据,直到换行符。
在任何一种情况下,您首先进行阅读,然后检查您是否实际阅读以及实际阅读了多少,然后检查您阅读的内容是否是您所期望的形式(例如字母数字)。
- 指向指向字符数组的指针数组的指针
- 比较字符数组
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 使用无符号字符数组有效存储内存
- 如何在C++中有效地将数字值重新分配给字符数组
- 在c++中读取文件时,它如何自动将字符放入字符数组,将数字放入整数变量
- 有没有办法将最初作为字符串输入的数字字符数组复制到双向链表中
- 查找字符数组中的数字总和
- C++ 计算字符数组中的数字数量
- 从字符数组中修剪非字母数字字符的功能
- 如何使用整数值中的数字符号初始化字符数组
- C++ 如何从标准输入加载到最多 5 个字母数字字符的字符数组
- 递增由不同分隔符分隔的字符数组中的数字
- C++如何将字符串转换为字符数组并检查数字
- 我将如何在不使用 if 语句、字符数组、apstring 或 atoi 的情况下将带有两位数字的字符串转换为 int
- 将字符数组拆分为字母数字字符和非字母数字字符
- 在字符数组中输入数字
- 将数字字符数组转换为整数
- 将圆周率的数字转换为字符数组(不含小数点){c++语言}
- 将整数的每个数字存储到可能的字符数组中