Home >Backend Development >C++ >How Can I Easily Extract Numbers from a Comma-Delimited String in C ?

How Can I Easily Extract Numbers from a Comma-Delimited String in C ?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-26 10:41:15848browse

How Can I Easily Extract Numbers from a Comma-Delimited String in C  ?

Easy Extraction of Numbers from Comma-Delimited Strings in C

Parsing a string containing a comma-separated list of numbers into an integer array is a straightforward task in C . To accomplish this, consider the following technique:

Iterate through the string character by character:

  • Input each number.
  • If the character following the number is a comma, discard it.

Code Implementation:

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

int main() {
  std::string str = "1,2,3,4,5,6";
  std::vector<int> vect;

  std::stringstream ss(str);

  for (int i; ss >> i;) {
    vect.push_back(i);
    if (ss.peek() == ',')
      ss.ignore();
  }

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

Output:

1
2
3
4
5
6

This code successfully parses the comma-delimited string into an integer array, storing the individual numbers in the vector vect. The std::stringstream makes it easy to extract the numbers and check for the presence of commas.

The above is the detailed content of How Can I Easily Extract Numbers from a Comma-Delimited String in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn