0
#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?

Mdjon26
  • 2,145
  • 4
  • 19
  • 29
  • 2
    http://stackoverflow.com/questions/4917265/can-i-tell-if-a-stdstring-represents-a-number-using-stringstream – Ben Mar 26 '14 at 15:03
  • This is not idiomatic. Use `remove_if`. – Engineer2021 Mar 26 '14 at 15:06
  • You have two seperate problems: 1) splitting a string at comma 2) checking if a string is a number. Make sure you split the problems and in your code. The first one is usually called tokenizing, the second one Bens link solves. – dutt Mar 26 '14 at 15:06
  • That code seems to work as-is on ideone.com. Exactly what input are you having problems with? – molbdnilo Mar 26 '14 at 15:10

3 Answers3

1

Use

std::getline(std::cin, str);

instead of

cin >> str;

Your string is getting tokenized to just the first "word". getline() reads in the whole line into str.

ugo
  • 2,705
  • 2
  • 30
  • 34
Farnsworth
  • 31
  • 3
0

Run the program in debug, and set a breakpoint at

cout << "error\n";

If it doesn't halt there for non-digit input, your compiler is buggy.
Your program, as far as I can tell, isn't. (apart from that it doesn't capture the last element, unless you terminate the input with ',')

Also check that you don't include any third-party header that redefines isdigit

sp2danny
  • 7,488
  • 3
  • 31
  • 53
0

Use STL function instead C-style function. Look at http://www.cplusplus.com/reference/string/stod/

Mayhem50
  • 165
  • 2
  • 8