I need a C++ code that split one string to other string by comma-separated word
- User
I need a C++ code that split one string to other string by comma-separated word
- Assistant
Here is an example code that split one string to other string by comma-separated word in C++:
#include <iostream> #include <string> #include <vector> #include <sstream> using namespace std; vector<string> split(string str, char delimiter) { vector<string> internal; stringstream ss(str); string tok; while(getline(ss, tok, delimiter)) { internal.push_back(tok); } return internal; } int main() { string input_str = "apple,banana,orange"; vector<string> words = split(input_str, ','); for(string word : words) { cout << word << endl; } return 0; }The
splitfunction takes in the input string and the delimiter character as arguments, and returns a vector of strings that contains the individual words.In the
mainfunction, we call thesplitfunction with the input string and comma delimiter. We then loop through the resulting vector and print out each word.Output:
apple banana orange - User
I need a C++ code that fast reads text file info same string
- Assistant
Here is an example code that reads a text file and stores its contents as a string in C++:
#include <iostream> #include <fstream> #include <string> using namespace std; int main() { string filename = "example.txt"; string file_contents; ifstream file(filename); if (file.is_open()) { file.seekg(0, ios::end); file_contents.reserve(file.tellg()); file.seekg(0, ios::beg); file_contents.assign((istreambuf_iterator<char>(file)), istreambuf_iterator<char>()); file.close(); cout << file_contents; } else { cout << "Unable to open file"; } return 0; }The code reads the contents of a text file with the name
example.txtand stores it as a string variablefile_contents.First, we open the text file using
ifstream. We then check if it was successfully opened. Next, we usefile.seekg(0, ios::end)to move the file pointer to the end of the file and calculate its size using . We reserve the required space in memory for using . We then move the file pointer back to the beginning of the file using and use function to insert the contents of the file into .