I have a file that contains a set range of numbers for example 20. The contents of the file are social security numbers, I am trying to erase every '-'. Though while going through the file I am receiving the following error.
libc++abi.dylib: terminating with uncaught exception of type std::out_of_range: basic_string
Here is the code
string str;
ifstream inFile (fName);
//fName= name of the file
if (inFile.is_open())
{
while ( getline (inFile,str) )
{
cout << str << endl;
str.erase(3,1);//erasing first '-'
str.erase(5,1);//erasing second '-'
cout << str << endl;
}
inFile.close();
}
else
cout << "Unable to open file";
I suggest adding some checks to your code so you don't assume there are two '-'
s where you expect to find them.
if ( str.size() >= 4 && str[3] == '-' )
{
str.erase(3,1);
if ( str.size() >= 6 && str[5] == '-' )
{
str.erase(5,1);
}
else
{
std::cout << "Did not find a '-' at the 6-th position of the string.\n";
std::cout << str << std::endl;
}
}
else
{
std::cout << "Did not find a '-' at the 4-th position of the string.\n";
std::cout << str << std::endl;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.