首页 > 解决方案 > 运行程序的奇怪输出

问题描述

我写了一些关于数组和字符串的代码,我不习惯使用这些代码(我是新手)。这个错误是一个运行时问题,因为当这个程序编译时编译器没有对我大喊大叫。我完全被这件事困住了,不知道为什么会这样。

# 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.

接下来是向微软团队报告的弹出窗口。

标签: c++arraysstringchar

解决方案


检查“at”并再次仔细查看一些程序员花花公子的评论:
http ://www.cplusplus.com/reference/array/array/at/

 It throws out_of_range if n is out of bounds.

哦,请,尤其是在问别人时: 不要使用 1 字母变量
不要使用难以解释的变量名称,例如“count”或“rec”


推荐阅读