C++ Separate a string by spaces and commas

I am trying to read in a text file, separate the integer values by commas and white spaces " ," and add each individual integer excluding " ," to a vector of integers. The following code only prints the first value. What am I doing wrong?

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;

int main()
{
std::vector<int> vecOfStrs;
std::ifstream fileIn("Scores.txt");
std::string str;

while (std::getline(fileIn, str)) {
    if (str.size() > 0) { //If there is any string at all do...

        std::stringstream ss(str); //std operator that turns str string into a stringstream to be operated on
        for (int i; ss >> i;) {
            vecOfStrs.push_back(i);
            if (ss.peek() == ' ,')
                ss.ignore();
        }
    }
}

fileIn.close();

for (size_t i = 0; i < vecOfStrs.size(); i++) {
    std::cout << vecOfStrs[i] ;
}

return 0;
}

And here is the text file "scores.txt" ::

76, 89, 150, 135, 200, 76, 12, 100, 150, 28, 178, 189, 167, 200, 175, 150, 87, 99, 129, 149, 176, 
200, 87, 35, 157, 189

I figured it out if anyone happens upon this looking for an answer. Use

if (ss.peek() == ',' || ss.peek() == ' ')

to check if it is a white space or a comma instead of

if (ss.peek() == ' ,')

C Programming Tutorial for Beginners, Learn C the Hard Way: Practical Exercises on the Computational Subjects You Keep Avoiding (Like C) Stock analysis for Citigroup Inc (C:New York) including stock price, stock chart, company news, key statistics, fundamentals and company profile.

Change your for loop to this and it'll work! Tested it on my side with the rest of your code.

for(string i; ss >> i;)//treat as string for string manipulation
{
    size_t pos=str.find(',');  //look for a comma
    if(pos!=std::string::npos) i.erase(pos); //if comma is found, erase it!
    vecOfStrs.push_back(stoi(i));  //convert string to integer
}

Basically: read it as a string, find() and erase() what you don't want and then use that as input.

One problem that I found in your code is that you were peeking for 2 characters. You should only peek for 1 character (see std::istream::peek). I assume that's what caused unexpected behaviour.

Cheers!

"C" Programming Language: Brian Kernighan, This course will give you a full introduction into all of the core concepts in the C programming Duration: 3:46:13 Posted: Aug 15, 2018 Discover historical prices for C stock on Yahoo Finance. View daily, weekly or monthly format back to when Citigroup, Inc. stock was issued.

There is no need to resort to peek() and ignore().

You could simply replace all commas with a space, and then use std::istringstream.

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

int main()
{
   std::vector<int> vecOfStrs;
   std::string str = "76, 89, 150, 135, 200, 76, 12, 100, 150, 28, 178, 189, 167, 200,"
                      "175, 150, 87, 99, 129, 149, 176, 200, 87, 35, 157, 189";

   // replace all commas with a space
   std::replace(str.begin(), str.end(), ',', ' ');                      

   std::stringstream ss(str); 
   for (int i; ss >> i;) 
       vecOfStrs.push_back(i);

   // output results
   for (size_t i = 0; i < vecOfStrs.size(); i++) 
       std::cout << vecOfStrs[i] << "\n" ;
}

Live Example

Learn C, "C" is one of the most widely used programming languages of all time. Prof Brian Kernighan Duration: 8:26 Posted: Aug 18, 2015 C programming is a general-purpose, procedural, imperative computer programming language developed in 1972 by Dennis M. Ritchie at the Bell Telephone Laboratories to develop the UNIX operating system. C is the most widely used computer language. It keeps fluctuating at number one scale of popularity

This should work. It parses the file line by line, matching all of the required strings then converting them to an int while adding them to the std::vector.

#include <regex>
#include <string>
#include <vector

   int main()
    {
        std::ifstream fileIn("Scores.txt")
        std::string str;
        std::regex words_regex("[^, ]+");
        std::vector<int> vecOfStrs();

        while (std::getline(fileIn, str)) 
         {
            if (str.size() > 0) 
           {
              auto words_begin = std::sregex_iterator(s.begin(), s.end(), words_regex);
              auto words_end = std::sregex_iterator() 
              for (std::sregex_iterator i = words_begin; i != words_end; ++i)                             
                 vecOfStrs.emplace_back(std::stoi(*i.str())); 

           }   
       }

    }

Learn C Programming, learn-c.org is a free interactive C tutorial for people who want to learn C, fast. Programming Languages Development - C++ has been used extensively in developing new programming languages like C#, Java, JavaScript, Perl, UNIX’s C Shell, PHP and Python, and Verilog etc. Computation Programming - C++ is the best friends of scientists because of fast speed and computational efficiencies.

C Tutorial, Tutorials Examples References Compiler. C is a powerful general-purpose programming language. It can be used to develop software like operating systems, databases, compilers, and so on. Learn about C with our data and independent analysis including price, star rating, valuation, dividends, and financials. Start a 14-day free trial to Morningstar Premium to unlock our take on C.

C Language - Overview, C programming is a general-purpose, procedural, imperative computer programming language developed in 1972 by Dennis M. Ritchie at the Bell Telephone� C - switch statement - A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is chec

Cprogramming.com: Learn C and C++ Programming, C Language - Overview - C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system � Microsoft C++, C, and Assembler documentation. Learn how to use C++, C, and assembly language to develop applications, services, and tools for your platforms and devices.

Comments
  • Side note: Single quotes denote a character. ' ,' tries to stuff 2 characters into a single character. The results of this are somewhat odd. Most compilers will give a warning. Don't ignore the warnings. They are the first line of defense against logic errors.
  • You could have done just a std::replace of all commas with a space, and then use std::istringstream without all of those peek calls.
  • This isn't quite a complete solution. This code alone will detect the space in the input stream and ignore it. This leaves the comma in the input stream to be picked up by ss >> i, and ss >> i cannot parse a comma. It needs to be wrapped in a loop.