Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

newb question....

Name: Anonymous 2006-04-11 18:08

Check this c++ code:

    string file_opened ("lol.txt");
    ofstream communism;
    communism.open (file_opened);

The thing keeps writing to a file called file_opened rather than lol.txt.  How do I get the thing to treat the variable as the string that makes it up?  Tutorials say nothing about this...  They always just show you how to write strings directly to output.

Also, while I'm at it, (I suspect this is related) if I wanted to generate the names of variables using code, how would I do it?  Say I wanted to initialize ten variables, name1 - name10, but I didn't feel like typing out every one.  Here's what I would write intuitively: 

while (i < 9)  {
    i+=1;
    int namei;
};

But I know this isn't right.

Name: Anonymous 2006-06-25 14:35

>>24

I left my Stroustrup book at work, but I'll see how well I remember from memory.

The method .c_str() returns a C-style string based on the contents of the string object that calls .c_str().  A C-style string is a null-terminated character array (example: "Hello" --> 'H' 'e' 'l' 'l' 'o' '\0'.).  In C (and in C++), a pointer can be used to point to an array.  For example:


//C-style code to output all chars.  Not the way I'd code myself
void outputAllChars(char *outputStr)
{
   while(outputStr)  //Loop until current Char == '/0' or NULL
          //Is it %c for a char?  We could always just use cout anyways
      printf("%c\n", outputStr++);  //Output AND go to next char
}


void outputStr(char outputStr[])
{
   int i = 0;
   while(outputStr[i] != '/0')
   {
      cout << outputStr[i] << endl;
      i++;
   }
}

Anyways, the point is, a pointer to an array or an array (i.e. []) are the same thing.  This is less important to worry about in C++ than in C.

Name: Anonymous 2010-09-21 17:11

Guys, please use code tags. Shit.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List