#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
string str, temp;
cout << "enter string: \n";
getline (cin, str);
vector<int> vec;
int num;
cout << "str size is " << str.size() <<endl;
for (int j=0; j < str.size(); j++)
{
int num2= str.size()-1;
if (isdigit(str[j]))
{
temp+= str[j];
num = atoi(temp.c_str());
if (num2 ==j)
vec.push_back(num);
}
else if (str[j] == ',')
{
num = atoi(temp.c_str());
temp.clear();
vec.push_back(num);
}
else
{
cout << "error\n";
temp.clear();
}
}
for (int k=0; k < vec.size(); k++)
cout << vec[k] <<endl;
}
I'm trying to make a program to where it reads in a string such as
5,6,7,8,11,120
and it'll separate the numbers from the commas, but if anything else is in the string it'll report it as an error. For example, if it was 5,6,f or 5, ,3 (space).
My program is not working though and I think it has something to do with when I am checking if it's a digit with the (isdigit) function. as it is counting fs, sds, xdx as a digit. Any idea how I can fix this?
EDIT: I've updated my code but I am still coming across problems. If I type in for example: 3,2,f it's saying that f is 0. How can I fix this?