来自运行程序的奇怪输出

时间:2019-04-05 11:47:34

标签: c++ arrays string char

我已经写了一些关于数组和字符串的代码,我不愿意使用它们(我是新手)。该错误是运行时的问题,因为在编译该程序时编译器没有对我大喊大叫。我对此一无所知,也不知道为什么会这样。

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

随后出现的是向Microsoft团队报告的弹出窗口。

1 个答案:

答案 0 :(得分:0)

选中“ at”,然后仔细查看一些程序员的兄弟评论:
http://www.cplusplus.com/reference/array/array/at/

 It throws out_of_range if n is out of bounds.

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