Faken
Faken

Reputation: 11822

Can't specify a file path prefix in program

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

Upvotes: 0

Views: 439

Answers (4)

Loki Astari
Loki Astari

Reputation: 264551

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.

Upvotes: 1

Jerry Coffin
Jerry Coffin

Reputation: 490308

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.

Upvotes: 0

Greg Domjan
Greg Domjan

Reputation: 14115

\ 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\\";

Upvotes: 2

lalli
lalli

Reputation: 6303

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.

Upvotes: 2

Related Questions