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
Release: 2024-11-26 07:13:10
Original
1020 people have browsed it

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;
}
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template