Home > Backend Development > C++ > How Can I Use Stringstream to Split Comma-Separated Strings in C ?

How Can I Use Stringstream to Split Comma-Separated Strings in C ?

Barbara Streisand
Release: 2024-12-04 07:21:12
Original
750 people have browsed it

How Can I Use Stringstream to Split Comma-Separated Strings in C  ?

Separating Comma-Separated Strings Using a Stringstream

In C , a stringstream is a stream that operates on a string object. It can be used to read from or write to a string. One common use case of a stringstream is to split a string into tokens.

Using Stringstream to Separate Strings by Commas

The standard stringstream operators, such as the >> operator, can be used to separate strings by whitespace. However, it cannot be used to separate strings by other delimiters, such as commas. To overcome this limitation, an alternative approach can be used.

The getline() function of the istringstream class can be used to read a line from the stringstream until a delimiter is encountered. By specifying a comma (',') as the delimiter in the getline() function, it is possible to split the input string into tokens separated by commas.

Example

The following code shows how to use a stringstream to separate comma-separated strings:

#include <iostream>
#include <sstream>

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

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

This code will produce the following output:

abc
def
ghi
Copy after login

Using the getline() function with a specified delimiter provides a convenient way to split comma-separated strings into individual tokens using a stringstream.

The above is the detailed content of How Can I Use Stringstream to Split 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