如何处理浮点异常?

时间:2017-01-22 06:07:38

标签: c++

我正在创建一个用于在字符串中旋转特定数字的代码,最初我为一个用户输入创建了它!一旦我在多个测试用例的逻辑上添加它就会显示浮点异常.....

任何人都可以在代码中告诉我导致该错误的原因!

#include<iostream>
#include<cstring>
using namespace std;
void stringrot(char str[],int n)
{   

    int l=strlen(str);
    char temp[100];
    int k=n%l;
    for(int i=0;i<k;i++)
    {
        temp[i]=str[(l-k+i)];
    }
    for(int i=0;i<l-k;i++)
    {
        temp[k+i]=str[i];

    }
    temp[l]='\0';
    cout<<temp;


}
int main()
{   
    int test;
    cin>>test;
    while(--test>=0)
    {   
        char str[100];
        cin.getline(str,50);
        int n;
        cin>>n;
        stringrot(str,n);
    }
}

这是代码!

2 个答案:

答案 0 :(得分:1)

让我们仔细看看main

中的while循环
while(--test>=0)
{   
    char str[100];
    cin.getline(str,50);
    int n;
    cin>>n;
    stringrot(str,n);
}

循环迭代1

    cin.getline(str,50); << reads a line
    cin>>n;              << reads an integer. After enter is pressed. Enter 
                            is not an integer. Enter is not read and stays 
                            in the stream
    stringrot(str,n);

循环迭代2

    cin.getline(str,50); << reads a line. Fortunately there is an enter
                            still in the stream making it really easy to 
                            find the end of the line. It's the first 
                            character that's going to be read.
    cin>>n;              << reads an integer. Unfortunately the user 
                            probably thinks they are typing in the string 
                            and doesn't type in a number. Oops. 
    stringrot(str,n);

无论如何stringrot会被stringrot("",0)调用,因此stringrot的前几行看起来像

int l=strlen("");   << l will be zero because the string is emtpy
char temp[100];
int k=n%l;          << resolves to 0%0 and an integer divided by zero is BOOM!

解决方案:

将while循环的内容更改为

char str[100];
cin.getline(str,50);
int n;
cin>>n;
// discard everything else on the line including the end of line character
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
stringrot(str,n);

为什么整数除法会导致浮点错误,顺便说一句,这不是一个可捕获的C ++异常,似乎主要是历史错误。更多信息:Why is this a floating point exception?

建议:

使用std::string而不是char数组。

答案 1 :(得分:0)

#include<iostream>
#include<cstring>
using namespace std;
//void stringrot(char str[],int n)
void stringrot(string str,int n)
{

    //int l=strlen(str);
    int l=str.size();
    char temp[100];
    int k=n%l;
    for(int i=0;i<k;i++)
    {
        temp[i]=str[(l-k+i)];
    }
    for(int i=0;i<l-k;i++)
    {
        temp[k+i]=str[i];

    }
    temp[l]='\0';
    cout<<temp;


}
int main()
{
    int test;
    cin>>test;
    while(--test>=0)

    {
        //char str[100];
        //cin.getline(str,50);
        string str;
        cin>>str;
        int n;
        cin>>n;
        stringrot(str,n);
    }
}