problem with argument types
May 16, 2008 at 7:17pm UTC
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 34 35 36 37 38 39 40 41 42 43 44 45 46 47
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
void inputFileInfo(string&, int &);
void displayFileInfo(string&, int &);
int main()
{
ofstream fsOut;
string fileID;
char str[100];
int lineCount = 0;
int currentLine = 0;
inputFileInfo(fileID, lineCount);
fsOut.open(fileID, ios::out | ios::app);
while (currentLine <= lineCount)
{
cin.getline(str, sizeof (str));
fsOut << str << endl;
currentLine++;
}
fsOut.close();
return 0;
}
void inputFileInfo(string& fileName, int & lines)
{
cout << "Enter name of file: " ;
cin >> fileName;
cout << "Enter number of lines to add: " ;
cin >> lines;
}
void displayFileInfo(string& fileName, int & lines)
{
cout << "File: " << fileName << endl;
cout << "Number of lines added: " << lines << endl;
}
I know why this code doesn't work: fsOut.open can't take a string as an argument. But although it can take a character array as an argument, my functions (most importantly, inputFileInfo) won't work because they take strings by reference. Is there a way to pass character arrays by reference, or a better solution to the argument incompatibility?
May 16, 2008 at 7:24pm UTC
C++ strings have a method that converts them to C-style strings. Try fsOut.open(fileID.c_str(), ios::out | ios::app);
May 17, 2008 at 1:12pm UTC
Thanks. That solved the problem quite nicely.
Topic archived. No new replies allowed.