outputting array as string

closed account (4ET0pfjN)
Hi, I want to output array elements in a string and store to a text file, but it's outputting weird symbols

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
string printList(int *list, int numElem)
{
	string sortedList = "";
	//NOW OUTPUT the sorted list
	for ( int k = 0; k < numElem; k++ )
	{
		sortedList+=list[k];
			
		if ( k != numElem - 1 )//We don't need a comma for last item
			sortedList+=" , ";
	}
	return sortedList;
}

int main()
{
  int arraySize = 10;
  int insertionList[10] = {10,9,8,7,6,5,4,3,2,1};
  insertionSort(insertionList, arraySize);//my own fcn for insertion sort
  
  ofstream myFile;
  myFile.open("insertionSorted.txt");
  string sortedList = printList(insertionList, arraySize);
  
  for ( int i = 0; i < arraySize; i++ )
  {
    myFile << sortedList;
  }
}
Last edited on
You can't append an integer to a string with +=:

sortedList+=list[k];

Instead, create a string stream and send stuff to it:

1
2
3
4
5
6
7
#include <sstream>

stringstream out;

out << list[k];

return out.str();
Topic archived. No new replies allowed.