0

In visual basic I have the following 2 strings:

"\\.\" & "\"

How do I represent them in C?
Also, & in VB is the concatenation operator?

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794

3 Answers3

4

Like this:

"\\\\.\\"
"\\"
pcent
  • 1,929
  • 2
  • 14
  • 17
3

The \ is an escape character so if you want to print \ you need to put two of them: \\

To concatenate two string you can use strcat(string1, string 2) which is shown here.

Billy ONeal
  • 104,103
  • 58
  • 317
  • 552
Kyra
  • 5,129
  • 5
  • 35
  • 55
  • 1
    -1: C has no concatenation operator. The C++ string class overrides operator+ to provide similar functionality, but by no means is that a core language operator even in C++. – Billy ONeal Jun 22 '10 at 16:30
  • +1 for the edited answer. @Billy ONeal, you might consider removing your downvote after the correction. – Fred Larson Jun 22 '10 at 16:35
  • I got the second part from a C tutorial. From http://www.java2s.com/Code/C/String/Demonstrateshowtoputstringstogetherusingstrcat.htm, http://www.roseindia.net/c-tutorials/c-str-con.shtml and http://stackoverflow.com/questions/308695/c-string-concatenation – Kyra Jun 22 '10 at 16:45
  • @Kyra: Yes, but I'd avoid `strcat` and the other `` facilities if at all possible (though no downvote for that :) ). – Billy ONeal Jun 22 '10 at 17:08
  • Two string literals, as in this question, can actually be concatenated simply by placing them next to each other. – caf Jun 23 '10 at 00:32
1

As others have said, the backslash character () in C is an escape character. Look at http://msdn.microsoft.com/en-us/library/h21280bw%28VS.80%29.aspx to find more about it.

So your strings come out as follows:

"\\.\" is "\\\\.\\"
"\" is "\\"

There are many ways to concatenate strings.

puts("Hello" " " "World");

will print "Hello World".

A common way is to use strcat().

char szBuff[60];                  /* szBuff is an array of size 60 */
strcpy(szBuff, "Hello");          /* szBuff contains "Hello" */
strcat(szBuff, " World");         /* szBuff contains "Hello World" */
strcat(szBuff, " from Michael");  /* now contains  the whole sentence */
strcpy(szBuff, "New message");    /* strcpy overwrites the old contents */
Michael J
  • 7,631
  • 2
  • 24
  • 30
  • Ok, but one should avoid the facilities in `` unless you have no other choice. – Billy ONeal Jun 22 '10 at 17:07
  • @Billy: Why? In C++ there are better ways, but in C is generally the preferred way to manipulate strings. How would you recommend doing it? – Michael J Jun 22 '10 at 22:09
  • If available I'd recommend writing them yourself using ways that accept a buffer length input, or using something like the Safe C String library M$ uses (strcpy_s, strcat_s, and friends). Why the C standard uses a method that allows such easy buffer overflows when length-prefixed strings were available does not make sense to me. – Billy ONeal Jun 22 '10 at 23:13