views:

32

answers:

4

In my program I am trying to construct a filename with a path to point to a particular folder where my data is stored. I have something that looks like this:

string directoryPrefix = "C:\Input data\";
string baseFileName = "somefile.bin";
string fileName = directoryPrefix + index + " " + baseFileName;

However the compiler keeps saying that I'm missing a semicolon at the end of the first line. How do I set this up properly so it would work?

Thanks

+2  A: 

You need to add escape charecters to every '\' to be accepted in a string.

string directoryPrefix = "C:\\Input data\\";

Visit this for a little more detail.

lalli
+2  A: 

\ is a special character

string directoryPrefix = "C:\Input data\"; you have special commands in the string \I and \" and so your string is not terminated

double up the \ to escape the escape character

string directoryPrefix = "C:\\Input data\\";

Greg Domjan
Ah, thanks. Well, so much for it being intuitive...
Faken
A: 

A couple answers have already mentioned doubling the backslashes. Another possibility is to use forward-slashes instead:

std::string directoryPrefix = "C:/Input data/";

Even though Windows doesn't accept forward slashes on the command line, it will accept them when you use them in a program.

Jerry Coffin
+1  A: 

As noted \ is a special escape character when used in string or character literal. You have too choices. Either escape the use of slash (so double slash) or move to the back slash which also works on all other OS so making your code easier to port in the future.

string directoryPrefix = "C:\\Input data\\";
string directoryPrefix = "C:/Input data/";

Or the best alternative is to move to a platform netural way of representing the file system.

Martin York