Can letters appear in the middle of the string? The answer to this determines whether you'll have to use 1 layer of stringstream, or 2 layers of stringstream.
Look up std::stringstream.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// Example program
#include <iostream>
#include <string>
#include <sstream>
int main()
{
// I know this isn't a complete solution, but shows std::stringstream in action.
std::istringstream iss("a -1 4 -1 -1 -1 -1 -1 8 -1");
std::string dummy;
iss >> dummy; // throw away the initial 'a'
int num;
while (iss >> num) // "while we're able to extract an int from the stringstream"
{
std::cout << "Parsed: " << num << '\n';
}
}
#include <iostream>
using std::cin;
using std::cout;
int
main()
{
int ch;
int sign {1};
while ((ch = cin.peek()) != EOF) {
if (isdigit(ch)) {
int num;
cin >> num; // read the number
num *= sign; // add the sign
cout << num << '\n'; // print it
sign = 1; // reset the sign
} else {
ch = cin.get(); // read one character
if (ch == '-') {
sign = -sign;
} elseif (ch == '+') {
;
} else {
sign = 1; // reset the sign
}
}
}
}