c++ - 运行程序的奇怪输出
问题描述
我写了一些关于数组和字符串的代码,我不习惯使用这些代码(我是新手)。这个错误是一个运行时问题,因为当这个程序编译时编译器没有对我大喊大叫。我完全被这件事困住了,不知道为什么会这样。
# include<iostream>
# include<cstdio>
# include<cstring>
# include<string>
using namespace std;
int main() {
char in[100];
gets(in);
int len = strlen(in);
std::string s(in);
int count = 0;
for (int i = 0; i < len; i++) {
if (s.at(i) == ' ') {
count += 1;
}
}
int i = 0;
char rec[100];
for (int j = 0; j < len; j++) {
if (s.at(j + 1) != ' ') {
i += 1;
rec[i] = s.at(j);
} else {
i += 1;
rec[i] = s.at(j);
}
}
for (int m = 0; m < i; m++) {
cout << rec[m];
}
//cout << count;
}
假设用户输入是“Hello World”(不带引号)。它本应返回“Hello”,但却收到如下错误消息:
terminate called after throwing an instance of 'std::out_of_range'
what(): basic_string::at
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
接下来是向微软团队报告的弹出窗口。
解决方案
检查“at”并再次仔细查看一些程序员花花公子的评论:
http ://www.cplusplus.com/reference/array/array/at/
It throws out_of_range if n is out of bounds.
哦,请,尤其是在问别人时: 不要使用 1 字母变量
不要使用难以解释的变量名称,例如“count”或“rec”
推荐阅读
- kubernetes-helm - helm charting - 如何多次渲染同一个模板?
- python - 从头开始执行主成分分析与 scikit-learn 不同地定位数据
- simplejson - 创建 /opt/ejson/keys 的权限被拒绝
- c++ - 从 C++ 中的字符串中删除特定元素
- vue.js - Eslint no-extra-parens 规则不起作用
- asp.net - 如何在 ASP .Net 中将值列表转换为数组?
- python - 在熊猫中动态替换所有列的最后一个字符
- java - calculate the percentage increase or decrease in a list of values in java
- python - 如何在 matplotlib 中注释单元格网格?
- python - 为什么 qlite3.OperationalError: no such column: loginsignup_customusers.password 在创建 CustomUser 和 CustomUserManager 时?