How to split string using istringstream with other delimiter than whitespace? - c++

The following trick using istringstream to split a string with white spaces.
int main() {
string sentence("Cpp is fun");
istringstream in(sentence);
vector<string> vec = vector<string>(istream_iterator<string>(in), istream_iterator<string>());
return 0;
}
Is there a similar trick to split a string with any delimiter? For instance, | in "Cpp|is|fun".

Generally speaking the istringstream approach is slow/inefficient and requires at least as much memory as the string itself (what happens when you have a very large string?). The C++ String Toolkit Library (StrTk) has the following solution to your problem:
#include <string>
#include <vector>
#include <deque>
#include "strtk.hpp"
int main()
{
std::string sentence1( "Cpp is fun" );
std::vector<std::string> vec;
strtk::parse(sentence1," ",vec);
std::string sentence2( "Cpp,is|fun" );
std::deque<std::string> deq;
strtk::parse(sentence2,"|,",deq);
return 0;
}
More examples can be found Here

#include <iostream>
#include <string>
#include <sstream>
int main()
{
std::istringstream iss { "Cpp|is|fun" };
std::string s;
while ( std::getline( iss, s, '|' ) )
std::cout << s << std::endl;
return 0;
}
Demo

The following code uses a regex to find the "|" and split the surrounding elements into an array. It then prints each of those elements, using cout, in a for loop.
This method allows for splitting with regex as an alternative.
#include <iostream>
#include <string>
#include <regex>
#include <algorithm>
#include <iterator>
using namespace std;
vector<string> splitter(string in_pattern, string& content){
vector<string> split_content;
regex pattern(in_pattern);
copy( sregex_token_iterator(content.begin(), content.end(), pattern, -1),
sregex_token_iterator(),back_inserter(split_content));
return split_content;
}
int main()
{
string sentence = "This|is|the|sentence";
//vector<string> words = splitter(R"(\s+)", sentence); // seperate by space
vector<string> words = splitter(R"(\|)", sentence);
for (string word: words){cout << word << endl;}
}

Related

How to accept an unknown number of lines in c++, each line has two strings

How do I accept an unknown number of lines in c++? Each line has two strings in it separated by a space. I tried the solutions mentioned in This cplusplus forum, but none of the solutions worked for me. One of the solutions works only when Enter is pressed at the end of each line. I am not sure if the \n char will be given at the end of my input lines. What are my options?
My current attempt requires me to press Ctrl+Z to end the lines.
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
using namespace std;
int main(){
string line;
while(cin>>line and cin.eof()==false){
cout<<line<<'\n';
}
return 0;
}
I would like to take an unknown number of strings as shown below:
cool toolbox
aaa bb
aabaa babbaab
Please don't flag this as a duplicate, I really tried all I could find! I tried the following solution on the above given link by m4ster r0shi (2201), but it did not work for me.
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<string> words;
string word;
string line;
// get the whole line ...
getline(cin, line);
// ... then use it to create
// a istringstream object ...
istringstream buffer(line);
// ... and then use that istringstream
// object the way you would use cin
while (buffer >> word) words.push_back(word);
cout << "\nyour words are:\n\n";
for (unsigned i = 0; i < words.size(); ++i)
cout << words[i] << endl;
}
And this other solution also did not work: other soln, and I tried this SO post too: Answers to similar ques. This one worked for my example, but when I pass only one line of input, it freezes.
// doesn't work for single line input
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
using namespace std;
int main(){
string line ="-1";
vector<string>data;
while(1){
cin>>line;
if(line.compare("-1")==0) break;
data.push_back(line);
line = "-1";
}
for(int i =0;i<data.size();i+=2){
cout<<data[i]<<' '<<data[i+1]<<'\n';
}
return 0;
}
If each line has two words separated by whitespace, then perhaps you should have a Line struct which contains two std::strings and overloads the >> operator for std::istream.
Then you can just copy from std::cin into the vector.
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
struct Line {
std::string first;
std::string second;
};
std::istream& operator>>(std::istream& i, Line& line) {
return i >> line.first >> line.second;
}
int main() {
std::vector<Line> lines;
std::copy(
std::istream_iterator<Line>(std::cin),
std::istream_iterator<Line>(),
std::back_inserter(lines)
);
for (auto &[f, s] : lines) {
std::cout << f << ", " << s << std::endl;
}
return 0;
}
A test run:
% ./a.out
jkdgh kfk
dfgk 56
jkdgh, kfk
dfgk, 56

Copying read value from txt to a vector [duplicate]

I am attempting to write a program which can read in a text file, and store each word in it as an entry in a string type vector. I am sure that I am doing this very wrong, but it has been so long since I have tried to do this that I have forgotten how it is done. Any help is greatly appreciated. Thanks in advance.
Code:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
int main()
{
vector<string> input;
ifstream readFile;
vector<string>::iterator it;
it = input.begin();
readFile.open("input.txt");
for (it; ; it++)
{
char cWord[20];
string word;
word = readFile.get(*cWord, 20, '\n');
if (!readFile.eof())
{
input.push_back(word);
}
else
break;
}
cout << "Vector Size is now %d" << input.size();
return 0;
}
One of the many possible ways is a simple:
std::vector<std::string> words;
std::ifstream file("input.txt");
std::string word;
while (file >> word) {
words.push_back(word);
}
operator >> takes care of only words divided by whitespaces (including new-lines) being read.
And in case you would be reading it by lines, you might also need to explicitly handle empty lines:
std::vector<std::string> lines;
std::ifstream file("input.txt");
std::string line;
while ( std::getline(file, line) ) {
if ( !line.empty() )
lines.push_back(line);
}
#include <fstream>
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <iterator>
using namespace std;
int main()
{
vector<string> input;
ifstream readFile("input.txt");
copy(istream_iterator<string>(readFile), {}, back_inserter(input));
cout << "Vector Size is now " << input.size();
}
Or, shorter:
int main()
{
ifstream readFile("input.txt");
cout << "Vector Size is now " << vector<string>(istream_iterator<string>(readFile), {}).size();
}
I'm not going to explain, because there's about a zillion explanations on StackOverflow already :)

How do I read a file into a 2D list by splitting at the comma

I'm working on a program where the user will input in the format x,0,0 and it will be saved to a file then read into an array where I can compare the values however I'm stuck when trying to read into a 2D array can someone please help? Think the error is in the struct part
This is what I have so far:
#include <iostream>
#include <string>
#include <fstream>
#include <cstring>
#include <sstream>
using namespace std;
struct listArray
{
string name[];
int price1[];
int price2[];
};
int main()
{
listArray la;
string line;
cout << "Enter your list: ";
ofstream fout;
fout.open("list.txt");
while (fout) {
getline(cin, line);
if (line == "-1")
break;
fout << line << endl;
}
fout.close();
int count = 0;
ifstream listFile;
listFile.open("list.txt");
if(listFile.is_open()){
while (listFile) {
getline(listFile, la.name[count], ",");
count++;
listFile.close();
}
}
You can use delimiter to grab the substring, and use this substring to fill your struct, an exemple of split:
#include<iostream>
std::vector<std::string> split(const string& input, const string& regex)
{
// passing -1 as the submatch index parameter performs splitting
std::regex re(regex);
std::sregex_token_iterator first{input.begin(), input.end(), re, -1},last;
return {first, last};
}
if you are using C++11 or higher, you can use std::vector for arrays, and you also can use boost library, they have nice support for delimiter and other stuffs.

Split String to Vector with Whitespaces c++ error

#include <iostream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
vector<string> split_string(string s)
{
string buf;
stringstream ss(s);
vector<string> tokens;
while (ss >> buf)
tokens.push_back(buf);
return tokens;
}
int main()
{
cout << split_string("Alpha Beta Gamma");
}
when i try to split a string into a vector by using whitespaces i am not able to print out my solution.
i doesnt let me use std::cout but in my function the return value is given
why cant i use it like that? how do i fix this?
std::cout cannot take a vector, you need to iterate through the container and print each element separately, try using something like this:
int main()
{
string originalString = "Alpha Beta Gamma";
for (const auto& str : split_string(originalString))
cout << str << '\n';
return 0;
}

Initializing a vector from a text file

I am attempting to write a program which can read in a text file, and store each word in it as an entry in a string type vector. I am sure that I am doing this very wrong, but it has been so long since I have tried to do this that I have forgotten how it is done. Any help is greatly appreciated. Thanks in advance.
Code:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
int main()
{
vector<string> input;
ifstream readFile;
vector<string>::iterator it;
it = input.begin();
readFile.open("input.txt");
for (it; ; it++)
{
char cWord[20];
string word;
word = readFile.get(*cWord, 20, '\n');
if (!readFile.eof())
{
input.push_back(word);
}
else
break;
}
cout << "Vector Size is now %d" << input.size();
return 0;
}
One of the many possible ways is a simple:
std::vector<std::string> words;
std::ifstream file("input.txt");
std::string word;
while (file >> word) {
words.push_back(word);
}
operator >> takes care of only words divided by whitespaces (including new-lines) being read.
And in case you would be reading it by lines, you might also need to explicitly handle empty lines:
std::vector<std::string> lines;
std::ifstream file("input.txt");
std::string line;
while ( std::getline(file, line) ) {
if ( !line.empty() )
lines.push_back(line);
}
#include <fstream>
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <iterator>
using namespace std;
int main()
{
vector<string> input;
ifstream readFile("input.txt");
copy(istream_iterator<string>(readFile), {}, back_inserter(input));
cout << "Vector Size is now " << input.size();
}
Or, shorter:
int main()
{
ifstream readFile("input.txt");
cout << "Vector Size is now " << vector<string>(istream_iterator<string>(readFile), {}).size();
}
I'm not going to explain, because there's about a zillion explanations on StackOverflow already :)