Reputation: 157
I'm new to C++ programming (haven't done it in 10+ since college.) and I'm trying to write a very basic program to grab a file name that has been passed as an argument. I'm just not getting how to get the file name. I'm using VS2012 Exp for Desktop.
Below is my code.
#include "stdafx.h"
#include <fstream>
#include <iostream>
#include <xstring>
#include <string>
//using namespace openutils;
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
wcout << "customconsole app has "<< argc <<" arguments passed. second one is: " << argv[1];
ofstream me_attach_file;
wstring newfilename = argv[1] && ".newext";
me_attach_file.open (".mailexpress");
me_attach_file << "Writing this to a file.\n";
me_attach_file.close();
return 0;
}
Upvotes: 1
Views: 1447
Reputation: 10495
&& doesn't add two strings together. The + operator does.
Also, C++ decides which of the many operator + functions to use by the type of the left-hand argument. You have two different types here, a _TCHAR string, a string literal ("this is a string literal") which is type char*, and you want to put it into a wstring.
First, a _TCHAR and char* aren't the same type, so it should be L".newext".
Second, you can't add two char*s, because that is adding two pointers, and pointer arithmatic does something different than what you want. So the first argument needs to be coverted to a wstring before you start adding things together.
Either:
wstring myStr = argv[1];
myStr += L".newext"
Or:
wstring myStr = wstring(argv[1]) + L".newext" + L"Additional stuff"
Upvotes: 3
Reputation: 370
in the line
me_attach_file.open (".mailexpress");
you should pass the filename to the object.
me_attach_file.open (newfilename);
in your version, ofstream will open a file named ".mailexpress" without prefix (which is hidden on unix systems).
Upvotes: 0
Reputation: 283941
Replace this
wstring newfilename = argv[1] && ".newext";
with
wstring newfilename = argv[1];
newfilename += L".newext";
Some languages use &
for string concatenation. C++ does not. In fact, there is NO operator that concatenates string literals and character pointers: +
as string concatenation is defined by string objects and works only with them.
In addition, string literals have to be prefixed with L
to use wide characters and be compatible with wstring
.
Upvotes: 3