Home >Backend Development >C++ >How Can `getline()` Be Used to Separate Comma-Separated Strings in C ?

How Can `getline()` Be Used to Separate Comma-Separated Strings in C ?

Linda Hamilton
Linda HamiltonOriginal
2024-11-26 07:13:101006browse

How Can `getline()` Be Used to Separate Comma-Separated Strings in C  ?

Exploiting getline() for Comma-Separated String Separation

To separate comma-separated strings in C , stringstream alone may not suffice. This article presents an alternative approach using the getline() method to achieve the desired separation.

In the given code, the stringstream::>> operator separates strings based on whitespace. To handle commas, you can incorporate getline() from the library. This method takes an istream object, a string variable to store the extracted token, and a delimiter character.

Consider the following modified version of the code:

#include <iostream>
#include <sstream>

int main() {
  std::string input = "abc,def,ghi";
  std::istringstream ss(input);
  std::string token;

  while (std::getline(ss, token, ',')) {
    std::cout << token << '\n';
  }

  return 0;
}

In this code, we use getline() to extract tokens from the stringstream by specifying a comma as the delimiter. The output is:

abc
def
ghi

By harnessing the capabilities of getline(), you can effectively separate strings by any specific delimiter, including commas. This approach offers greater flexibility and customization for string manipulation tasks.

The above is the detailed content of How Can `getline()` Be Used to Separate Comma-Separated Strings 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