strings- novice here

Working on a small script here but having some trouble getting a string to work. here is a code snipplet:
int itemscan;
srand((unsigned)time(0));
int salenumber = rand();
string filename;
ofstream datafile;
filename = "salelog-" << salenumber << ".pos";
datafile.open(filename.c_str());
datafile << "Transaction Details for:" << salenumber << "\n";
cout << "TRANSACTION | Transaction Id:" << salenumber << "\n";
cout << "Scan the first Item.\n";
cin >> itemscan;

i need the filename to say like salelog-(SALENUMBER VAR).pos. Everything i seem to do is failing. I have a book ordered but it wont be here untill next week
Last edited on
Firstly, you need to convert your number to a string before you can join it.

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

using namespace std;

int main() {

  int myNumber = 10;

  // Convert number to a string
  ostringstream myNumberString;
  if (!(myNumberString << myNumber)) {
    cout << "myNumberString isn't valid number: " << myNumber << endl;
    return 0;
  }

 // join them
 string fileName = "salelog-" + myNumberString.str() + ".pos";

 cout << fileName << endl;

 return 0;
}


If you ever try to choice multiple char[] variables together into a string this will fail. You need to do something like string x = "blah" + string("blah2") + "blah3" + string("blah4"); // etc . This is because there is no operator for joining 2x char[] together. But string has an operator to add a char[] to it.

In this case ostringstream.str() returns a string, so there is no problem :)

Hope that made sense :)
Last edited on
Topic archived. No new replies allowed.