Hello Everyone i am trying to write a program for printing all the combinations of a string.I do not want any help regarding the algorithm but i need help figuring out why this program is giving the error message
"First-chance exception at 0x761bc41f in word.exe: Microsoft C++ exception: std::out_of_range at memory location 0x0026f6b4..
Unhandled exception at 0x761bc41f in word.exe: Microsoft C++ exception: std::out_of_range at memory location 0x0026f6b4.." when i try to run this in MVS 2010

#include<iostream>
#include <stdio.h>
#include <string>
#include <stdlib.h>
#include<conio.h>
void combination(std::string input,int length,std::string buffer,int allowedno)
{
    for(int i =allowedno;i<length;i++)
    {
        buffer.at(i)=input.at(i);
        std::cout << buffer<< '\n';
        if(i!=length)
        {
        combination(input,length,buffer,i+1);
        }
        buffer.erase(length-1);
    }
}

void combine(std::string input)
{
int length=input.size();
//char *buffer = (char *)malloc(sizeof(char)*(length+1));
std::string buffer(input);
buffer.erase();
combination(input,length,buffer,0);
}



void main()
{
    std ::string input= "ABC";
    combine(input);
   getch();
}

Recommended Answers

All 3 Replies

In the function combination buffer is of size zero. It is a string object that contains no characters. You then try to change the first character like this:
buffer.at(i)=input.at(i);
The first character does not exist so an exception is thrown.

Does VS2010 let you get away with compiling this code? It predates the 1998 C++ standard and by modern standards is bad code that should not compile.

What Moschops said. This is why we do exception handling (try/catch/throw) in C++. That will allow you to detect this sort of error and terminate after output of a meaningful error message that will help you fix the problem.

thanks you,i assume modifying the line to
buffer.append(input.at(i));
will fix the error.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.