Reputation: 1
#include <vector>
#include <string>
#include <sstream>
#include <iostream>
int main()
{
std::string str = "1,2,3,4,5,6";
std::vector<int> vect;
std::stringstream ss(str);
for (int i=1; ss >> i;) {
vect.push_back(i);
if (ss.peek() == ',')
ss.ignore();
}
for (std::size_t i = 0; i < vect.size(); i++)
std::cout << vect[i] << std::endl;
}
I have this code. I'm trying to remove the first and last values from the string. I have tried deleting those values before getting to the for
loop but it doesn't work.
Upvotes: 0
Views: 142
Reputation: 117851
Here's an alternative to messing with the actual stringstream
. Extract the int
s and remove the first and last from the resulting vector.
#include <vector>
#include <string>
#include <sstream>
#include <iostream>
#include <iterator>
int main() {
std::string str = "1,2,3,4,5,6";
std::stringstream ss(str);
std::vector<int> vect;
while(ss) { // is the stream in a good state
if(int v; ss >> v) { // try to extract an int
vect.push_back(v); // success, save it
} else if(not ss.eof()) { // check that the stream is not depleated
ss.clear(); // clear the failstate
ss.ignore(); // ignore 1 char
} // else leave the stream in a failed state to exit the while loop
}
// erase the last int in the vector
if(not vect.empty()) vect.erase(std::prev(vect.end()));
// erase the first int in the vector
if(not vect.empty()) vect.erase(vect.begin());
for (int val : vect)
std::cout << val << '\n';
}
Upvotes: 2
Reputation: 7100
To remove the last and first characters from the string
str = str.substr(1, str.size() - 2);
Or
str.erase(str.begin());
str.erase(--str.end());
To remove the two last and two first characters from the string
str = str.substr(2, str.size() - 4);
Or
str.erase(str.begin(), str.begin()+2);
str.erase(str.end()-2, str.end());
Upvotes: 2