0

I am trying to figure out how to extract integers into an int vector so I can compute them:

input = 40,50,29,50

*take out the delimiter and separate the numbers into an array

arr[ ] = {40 50 29 50}

arr[0]+arr[1] = 90

I would love it without std:: (aka using namespace std; easier for me to understand)

Someone had an example here but I don't if it is the same thing or how to really understand it. There was also a suggestion using tokens but I am unsure how to do this either. Anything helps thank you!

  • 3
    Please, pretty please, search the internet for "C++ read file comma separated". There are already a plethora of examples out there. Always search the internet before posting to StackOverflow. If you are having issues with your code, post an [mcve] and change the title to something like "Trouble reading integers from CSV file"; something indicating we should inspect your code. – Thomas Matthews Jun 25 '20 at 02:19
  • 'I would love it without std' realize that typing using namespace std; is actually a bad habit in programming, even though it does help readability. – Telescope Jun 25 '20 at 02:31
  • Maybe you can change the delimiter for cin (https://stackoverflow.com/questions/7302996/changing-the-delimiter-for-cin-c) and read them normally as if they were space-separated. :) – Tortellini Teusday Jun 25 '20 at 02:35

1 Answers1

1

You can just store the whole input as a string, then loop through it and convert the substrings between the commas to integers:

#include <iostream>
#include <fstream>
#include <cmath>
#include <algorithm>
#include <vector>

using namespace std;

int main(){
    vector <int> nums;

    string str;
    cin >> str;

    int lastcomma = -1;
    while(str.find(',', lastcomma+1) != string::npos){ // find the next comma
        int curr = str.find(',', lastcomma+1);

        // stoi converts a string to an integer; just what you need
        nums.push_back(stoi(str.substr(lastcomma+1, curr - (lastcomma+1))));

        lastcomma = curr;
    }
    
    // get the last number
    nums.push_back(stoi(str.substr(lastcomma+1, str.size()-(lastcomma+1))));
  

    return 0;
}
Telescope
  • 2,068
  • 1
  • 5
  • 22