开发者

How to combine variable with string value

I want to combine variable with string value in (ofstream) file path

Example:

long phNumber;
char bufPhNumber[20];
ofstream ifile;

cout << "Phone Number: ";
cin >> phNumber;
itoa(phNumber,bufPhNumber,20);

ifile.open("c://" + bufPhNumber + ".txt",ios::out);  // error in this line
开发者_开发技巧

How to combine this variable (bufPhNumber) with that strings ( "c://" + variable here + ".txt" )


Do this:

ifile.open((std::string("c://") + bufPhNumber + ".txt").c_str(),ios::out);  

Explanation :

It first creates a string, and concatenates the rest of c-strings using operator+() as:

std::string temp = std::string("c://") + bufPhNumber + ".txt";

then takes c_str() and pass this to .open():

ifile.open(temp.c_str(),ios::out);  

However, in C++11, you don't need to do .c_str(), and you can use std::string directly.


A better solution should be this:

std::string phNumber; //declare it as std::string

cout << "Phone Number: ";
cin >> phNumber; //read as string

         //use constructor
ofstream ifile(("c://" + phNumber + ".txt").c_str(), ios::out);  


ofstream::open, at least before C++11 (a), requires a const char * for the file name, not a std::string, as per here.

Instead of:

ifile.open("c://" + bufPhNumber + ".txt",ios::out);

use the following:

string fspec = std::string ("c://") + bufPhNumber + ".txt";
ifile.open (fspec.c_str(), ios::out);

(and you may want to consider why your output file is called ifile).


(a) In C++11, there are two open functions for basic_ofstream:

void open(const char* s, ios_base::openmode mode = ios_base::out);
void open(const string& s, ios_base::openmode mode = ios_base::out);

so a string version would work there.


Okay, hi. You can't concatenate strings directly like in java, so your issue is here:

bufPhNumber + ".txt"

Given bufPhNumber is a char * and text is a char *, they don't support the + operator in the way that you intend.

There is strcat() for such a job, but it assumes the target string has enough room for the destination string, and it also modifies the target string.

char Array[28]; //One for the null
strcat(Array,"C:\\");
strcat(Array,bufPhNumber);
strcat(Array,".txt");

Although I recommend using a char array for phone numbers as long isn't very well suited for such storage as it can't hold as many digits as you like (you might consider using two ints/longs). Also, consider using unsigned long (as you don't get negative phone numbers). If you do use long/int, note that conversion from long to char array, and char array to long will take a chunk of memory and processing power, which on a bigger scale is less efficient than just using char arrays.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜