How can I 'stringstream' char data type array?

Feb 10, 2020 at 8:56pm
Hello, I am trying to combine two array of data type "char" as demonstrated below. So it seems if I do 'std::stringstream << array_char[i], this is not accepted. Is the problem here that stringstream would only accept data type string, correct?
If so, is there any equivalent of 'stringstream' applied to characters? So far I cannot find it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
   
#include <iostream>

int main()
{
	//Define arrays type char representing the month name and how many days on each month
	char array_char[12][20] = { "January", "February" ,"March", "April", "May", "June", "July"
							 , "August", "September", "October", "November", "December" };
	int array_days[12] = { 30, 29, 31, 30, 31, 30, 31, 30, 31, 30, 30, 31 };

	std::stringstream mychar;

	for (int i = 1; i < 13; i++) {
		mychar << array_char[i] << " ";
		mychar << array_days[i] << "\n";
	}

	std::cout << mychar.str();
}
Feb 10, 2020 at 9:22pm
you can cast a char array to string.
the char array functions (cstrings, we call them) are strcat, strlen, strstr, etc ... they mostly start with str...

you probably should not use char arrays, just use strings. If there is a legit reason to use arrays, casting to string is the way to do it. From there we can go backwards all the way to C until you are happy.
Last edited on Feb 10, 2020 at 9:23pm
Feb 10, 2020 at 9:23pm
As far as I can tell, that code is fine. It's only missing #include <sstream> . With that include added GCC accepts it.
Feb 10, 2020 at 9:26pm
Thank you, helios and all.
#include <sstream> did it!
Topic archived. No new replies allowed.