How to take a function using stringstream to parse the numbers, and put them into an array?

Related searches

So I am using stringstream in a function in c++ to take the numbers from a string, and then return the numbers to an array in main, but for some reason, they always return as 0 instead of the actual numbers. Code is below, does anyone know how to fix this?

int main()
{
for(int i = 0; i < userInput.length(); i++)
{
...
else
{
chemNumbers[i] = extractIntegerWords(userInput);
cout << chemNumbers[i] << endl;

}

}
int extractIntegerWords(string str)
{
    stringstream ss;
    int num = 0;

    ss << str;

    /* Running loop till the end of the stream */
    string temp;
    int found;
    if(!ss.eof())
    {

        ss >> temp;
        if (stringstream(temp) >> found)
        {
           num = found;
        }
        temp = "";

    }
    return found;
}

The original if statement doesn't pertain to the function only what is seen in the else statement, which is in main

This is off the top of my head and I don't have much time to test it, but this should put you in the right direction:

#include <iostream>
#include <string>
#include <sstream>
#include <vector>

using std::cout; 
using std::endl;
using std::istringstream;
using std::string;
using std::vector;

inline bool tryGetInt(const string& str, string& out) { istringstream sStream(str); return !(sStream >> out).fail(); } /*!< Tries to parse a string to int. */

void splitString(const string &str, const string &delimiters, vector<string> &tokens) {
    // Skip delimiters at beginning.
    string::size_type lastPos = str.find_first_not_of(delimiters, 0);
    // Find first "non-delimiter".
    string::size_type pos = str.find_first_of(delimiters, lastPos);

    while (string::npos != pos || string::npos != lastPos) {
        // Found a token, add it to the vector.
        tokens.push_back(str.substr(lastPos, pos - lastPos));
        // Skip delimiters.  Note the "not_of"
        lastPos = str.find_first_not_of(delimiters, pos);
        // Find next "non-delimiter"
        pos = str.find_first_of(delimiters, lastPos);
    }
}

int32_t main(int argCount, char* argValues[]) {
    for (int32_t i = 0; i < argCount; i++) {
        cout << "Found argument " << argValues[i] << endl;
        auto foundIntegers = getIntegerFromString(string(argValues[i]));

        // Do whatever
    }

    return 0;
}

vector<int64_t> getIntegerFromString(string formula) {
    vector<int64_t> foundInts;
    string temp;

    if (tryGetInt(formula, temp)) {
        vector<string> intsAsStrings;
        splitString(temp, " ", intsAsStrings);
        for (auto item : intsAsStrings) {
            foundInts.push_back(stol(item));
        }
    }

    return foundInts;
}

stringstream in C++ and its applications, str() — to get and set string object whose content is present in stream. stringstream class is extremely useful in parsing input. Number of words are: 6 each word it mapped to it's frequency Set 2 � C++ string class and its applications � INT_MAX and INT_MIN in C/C++ and Applications � strchr() function in C++ and its� Using this we can read from string as if it were a stream like cin. The Stringstream has different methods. These are like below − clear(): Used to clear the stream. str(): To get and set the string object whose content is present in stream. operator << : This will add one string into the stringstream

Regular expression might help:

std::vector<std::pair<std::string, std::size_t>> Extract(const std::string& s)
{
    std::vector<std::pair<std::string, std::size_t>> res;
    const std::regex reg{R"(([a-zA-Z]+)(\d*))"};

    for (auto it = std::sregex_iterator(s.begin(), s.end(), reg);
         it != std::sregex_iterator();
         ++it)
    {
        auto m = *it;
        res.push_back({m[1], m[2].length() == 0 ? 1 : std::stoi(m[2])});
    }
    return res;
}

int main()
{
    for (auto p : Extract("C6H12O6")) {
        std::cout << p.first << ": " << p.second << std::endl;
    }
}

Demo

Extract all integers from string in C++, Given a string, extract all integers words from it. The idea is to use stringstream: , objects of this class use a string buffer that contains a sequence of characters. Removing spaces from a string using Stringstream; Converting Strings to Numbers in C/C++; This article is contributed by ASIPU PAWAN KUMAR. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on

I add option for array instead vector for @I'mbadatCS

#include <vector>
#include <string>
#include <sstream>
#include <iostream>

using namespace std;

vector<int> extractIntegerWords(const string& _str)
//for array option: void extractIntegerWords(const string& _str, int* numArr)
{
    stringstream ss;
    ss << _str;    
    vector<int> vec;

    string temp;
    int found;
    //for array option: int idx = 0;

    while(!ss.eof())
    {
        ss >> temp;
        if (stringstream(temp) >> found)
        {
           vec.push_back(found);
           //for array option:numArr[idx++] = found;
        }
        temp = ""; 
    }

    return vec;
//for array option: return;
}

int main()
{
    string s = "bla 66 bla 9999 !"
    vector<int> res = extractIntegerWords(s);
    for (int i = 0; i < res.size(); ++i)
    {
        cout << res[i] << ", " << endl;
    }

}

a few comments:

  1. const string& in input argument, not string. you don't want harm your source data
  2. you need a loop not "if" (like ths the operation will run just one time)
  3. where your array??
  4. in C++ prefer use vector and not array

[PDF] Stringstreams & Parsing, CS 103 Unit 14 – Stringstreams C++ string library (#include <string> defines a global function (not a member of ifstream or delim = A char to stop on (by default it is '\n') which is why its called getline Use << and >> to convert numbers into strings Yes, Use a loop and extract (>>) values placing them in array or vector. Removing spaces from a string using Stringstream This article is contributed by Prakhar Agrawal . If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.

stringstream - C++ Reference, Objects of this class use a string buffer that contains a sequence of characters. This sequence of xalloc, Internal arrays to store objects of type long and void* . tied stream, tie seekg: Set position in input sequence (public member function ) . There are two common methods to convert strings to numbers: Using stringstream class or sscanf() stringstream() : This is an easy way to convert strings of digits into ints, floats or doubles. Following is a sample program using a stringstream to convert string to int.

StringStream Discussions | C++, Learn how to use stringstreams. Get me the next thing on the stream (which actually is a string) and put it in the all numbers, then exit the loop and return the vector to the calling function (in vector parseInts(string str) { stringstream ss( str); vector numbers; while why would it extract 44 and not 4 from array {44,23, 45}?. Here is constructed an unnamed stringstream object and performed the output ostringstream() << Number Then, since the << returns a reference to an ostream ( a base of ostringstream) the result of the operation needs to be casted back to a stringstream static_cast<ostringstream*> Finally, we get the contents of the resulting stream as a string ->str() and we assign that value to the string

In this program we will see how to parse comma-delimited string in C++. We will put a string where some texts are present, and they are delimited by comma. After executing this program, it will split those strings into a vector type object. To split them we are using the getline() function. The basic syntax of this function is like:

Comments
  • what is input, output and expected output? not clear why you use 2 stringstreams. Please dont include "Some more irrelevant code here" in the example, if some code is not relevant then remove it completely, but make sure the example still compiles and reproduces the error (see also minimal reproducible example)
  • as written this cannot compile because you define a function inside main. this is not allowed
  • The input is user input and should take the form of some sort of chemical compound like C6H12O6 and I want to take out each number and put it into a separate value of the array chemNumbers[i], I forgot to include that the if else is in a for loop.
  • you can edit the question to include the missing information and fix the code
  • Sorry fixed it, it does compile, it is declared outside of main i just messed up on the brackets, it just always prints out 0 for whatever is in chemNumbers[i].
  • Hi man this looks good, I just am not sure how vectors work just yet as I am still relatively new to C++, how would I call that in main?
  • in basicly, vector is array with auto managment. you can replace the "vector<int>" in int[10] (let's assume you know you have max 10 numbers, if you haven't any idea about it and there is option is a big amount you need dynamic allocoation). I add it to the answare