1

I have a string contains numbers but also contains spaces between them, i need to convert the string to int and store them in an int array .

Th following function produces a run time error

void fun(string  m)
{
    string temp;
    int j = 0;
    int h = 0;
    int d;
    int arr[10];
        for (int i = 0; i < m.length(); i++)
        {
            while (m[i] != ' ')
                temp[j++] = m[i];

            d = atoi(temp.c_str());
            arr[h++] = d;
        }

        for (int i = 0; i < sizeof(arr); i++)
        {
            cout << arr[i];
        }
}

4 Answers 4

1

I would suggest using a stringstream for this vs. rolling your own implementation.

#include <sstream>
#include <iterator>
#include <iostream>
int main()
{
    std::stringstream ss("1 2 3 4 5 6 7");
    auto head = std::istream_iterator<int>(ss);
    auto tail = std::istream_iterator<int>();
    while(head!=tail)
    {
        std::cout << *head << "\n";
        ++head;
    }
    return 0;
}

if you're receiving the string in a method you can easily adapt the function above to create an empty stringstream and then pass it the string.

#include <sstream>
#include <iterator>
#include <iostream>

int main()
{
    std::string astring = "1 2 3 4 5 6";
    std::stringstream ss;

    ss << astring;
    auto head = std::istream_iterator<int>(ss);
    auto tail = std::istream_iterator<int>();
    while(head!=tail)
    {
        std::cout << *head << "\n";
        ++head;
    }
    return 0;
}
Sign up to request clarification or add additional context in comments.

Comments

0

You are making several mistakes in your code.

  1. You have not initialized temp to contain anything, but you are trying to index into its characters. Instead of temp[j++] = m[i], you need to use temp += m[i]; or temp.push_back(m[i]); or temp.append(&m[i], 1);. Or consider using an std::ostringstream to gather the characters, and then call its str() method to extract the final std::string value.

  2. you are not incrementing i in your while loop. As soon as the for loop reaches a non-whitespace character, your while loop will end up running endlessly, continuously (and unsuccessfully) trying to append the same character to temp.

  3. you are not doing any bounds checking to make sure your for loop does not exceed arr's max capacity of 10 numbers.

  4. you are misusing sizeof(). sizeof(arr) returns the number of bytes that arr occupies in memory (10 * sizeof(int), which is 20 or 40 bytes, depending on your compiler's implementation of int). It is not the number of elements in the array (10). So you will exceed the bounds of the array trying to display 20/40 numbers instead of 10 numbers.

Your code is more complicated than it needs to be. You can use a std::istringstream for parsing and let it ignore whitespace for you. Use std::vector or other dynamically-sized container to receive the parsed numbers.

#include <sstream>
#include <vector>

void fun(string  m)
{
    std::istreamstream iss(m);
    std::vector<int> vec;
    int num;

    vec.reserve(10); // optional

    while (iss >> num) {
        vec.push_back(num);
    }

    for (int i = 0; i < vec.size(); ++i) {
        std::cout << vec[i];
    }
    /*
    alternatively:
    for (std::vector<int>::iterator iter = vec.begin(); iter != vec.end(); ++iter) {
        std::cout << *iter;
    }
    */
    /*
    alternatively (C++11 and later):
    for (auto i: vec) {
        std::cout << i;
    }
    */
    /*
    alternatively (C++11 and later):
    std::for_each(vec.begin(), vec.end(), [](int &n){ std::cout << n; });
    */
}

2 Comments

Thank you so much for your great answer, can you just give me what exactly istreamstream do ? I read more but still not clear for me
std::istringstream is an input stream for reading formatted data from a std::string. Similar to std::cin for console input, std::ifstream for file input, etc. I have added links to documentation for std::istringstream (and std::ostringstream and std::vector).
0

You cannot do for (int i = 0; i < sizeof(arr); i++)

The sizeof() operator gives you the size of something in bytes, which for an array of 10 ints probably amounts to 40. You need to use something like this:

#define COUNTOF(x) ((x)/sizeof((x)[0]))

for (int i = 0; i < COUNTOF(arr); i++)

2 Comments

I have change it to constant for (int i = 0; i < 4 ; i++) but still have an error
Well, then, that's probably a different error. Having one error in your code does not mean that it is the only error. It would greatly help if you explained precisely what error you get, precisely on which line, and precisely with what value of m.
0

The problem is in your while loop, J is 0 the first iteration through the While loop and gets incremented the first time it's called while also trying to assign it to the next letter.

Despite this issue I'd suggest using a string stream for this problem like others have said. Here's a good reference.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.