Comma separated string to Array in C++
Hello, guys in this tutorial we will learn how to insert comma-separated string to an array in C++. To understand a topic we need to look at some examples.
Convert comma separated string to array in C++
Example 1 input string s="i,love,my,country,very,much" output i love my country very much
Example 2 input string s="i,like,coding" output i like coding
We need to understand something before moving further.
getline()
It is a function that comes under <string> header file. It used to read string but it is different because it read the whole line no matter blank spaces between a string.
#include<iostream> #include<string> using namespace std; int main() { string s; // declare string variable cin>>s; //taking string as input cout<<s<<endl; //printing string }
input Hello world output Hello
Notice one thing in above we have given “Hello world” as input but the output is “Hello” it is because whenever there is space encounter between string compiler thinks a line is over so it does not take rest of string so to overcome this problem we use getline() function.
#include<iostream> #include<string> using namespace std; int main() { string s; //declare a string variable getline(cin,s); // calling getline fuction cout<<s<<endl; //printing a string }
input Hello world output Hello world
In the above example, the whole string is printed
String stream
The string stream is a class that works with strings and it comes under <sstream> header file We can read the string through its object. We will use good() function that will check if the string stream is error-free or not.
Code-
#include <vector> #include <string> #include <sstream> #include <iostream> using namespace std; int main() { string s="i,love,my,country,very,much"; //declare a string string answer[6]; // string array to store the result stringstream string_stream(s); // creating string stream object int i=0; // declaring i and assign to 0 while(string_stream.good()) // loop will continue if string stream is error free { string a; getline( string_stream, a, ',' ); //calling getline fuction answer[i]=a; i++; } for(i=0;i<6;i++) { cout<<answer[i]<<endl; // printing a result } return 0; }
output i love my country very much
Also read:
Leave a Reply