Reputation: 11
I am trying to assign characters from one string to other using function but I am getting error.
"terminate called after throwing an instance of 'std::out_of_range' what(): basic_string::at: __n (which is 0) >= this->size() (which is 0)"
#include <iostream>
#include <string>
#include <vector>
void split (std::string line)
{
std::string::size_type leng=0;
leng=line.length();
std::string k;
for (long unsigned int i=0;i<leng; i++)
{
k.at(i)=line.at(i);
}
std::cout<<k;
}
int main()
{
std::string line = "";
std::cout << "Enter a string: ";
getline(std::cin, line);
split(line);
}
Upvotes: 1
Views: 138
Reputation: 11
You are trying to access an element of an empty string, please use this code.
#include <iostream>
#include <string>
void split (const std::string& line) // pass parameter by reference to avoid copy
{
std::string::size_type leng = line.length();
std::string k;
k.resize(leng); // use resize to create space for the new characters
for (long unsigned int i = 0; i < leng; i++)
{
k.at(i)=line.at(i);
}
std::cout << k;
}
int main()
{
std::string line = "";
std::cout << "Enter a string: ";
getline(std::cin, line);
split(line);
}
Upvotes: 0
Reputation: 5202
#include <iostream>
#include <string>
void split (std::string line)
{
std::string::size_type leng = line.length();
std::string k;
for (long unsigned int i = 0; i < leng; i++)
{
k.push_back(line.at(i)); // This is the only real change
}
std::cout << k;
}
int main()
{
std::string line = "";
std::cout << "Enter a string: ";
getline(std::cin, line);
split(line);
}
When k
is declared, it is empty. It's size is therefore 0. You are using the .at()
function, which accesses a specific element (character) and throws an exception when you go out of bounds. You immediately go out of bounds because k
is empty.
Now, your function doesn't split (yet, or you left that part out), but .push_back()
seems like it will fit what you're trying to do best. It will add the characters to the end of the string, and grow the string as needed; you won't have to worry about manually managing its size.
Upvotes: 1
Reputation: 98
This exception is thrown because any new string that is created whitout initial content, have 0 len.
Accessing characters via at()
expect that index have a character, but the k
have no no value even at 0.
You can resize the string first, and then use at()
std::string k;
k.resize(leng);
Upvotes: 1
Reputation: 11340
When you initialize k
it is an emtpy string. So k.at(i)
will be out of of bounds as the error message says.
There are plenty of ways to copy a string, you could use a constructor like std::string k(line);
or k.assign(line)
or you could use resize() to resize k
before the loop.
Upvotes: 4