Mark Lalor
Mark Lalor

Reputation: 7887

C++ concatenate string problem

Why does the following code not work?

#include <iostream>
#include <string>
int main(){
    char filename[20];
    cout << "Type in the filename: ";
    cin >> filename;
    strcat(filename, '.txt');
    cout << filename;
}

It should concatenate ".txt" on the end of whatever filename is inputted

Also, when I try to compile it (with g++) this is the error message

alt text

Upvotes: 1

Views: 3007

Answers (3)

In silico
In silico

Reputation: 52159

Use double quotes instead of single quotes.

strcat(filename, ".txt"); 

In C++, single quotes indicate a single character, double quotes indicate a sequence of characters (a string). Appending an L before the literal indicates that it uses the wide character set:

".txt"  // <--- ordinary string literal, type "array of const chars"
L".txt" // <--- wide string literal, type "array of const wchar_ts"
'a'     // <--- single ordinary character, type "char"
L'a'    // <--- single wide character, type "wchar_t"

The ordinary string literal is usually ASCII, while the wide string literal is usually some form of Unicode encoding (although the C++ language doesn't guarantee this - check your compiler documentation).

The compiler warning mentions int because the C++ standard (2.13.2/1) says that character literals that contain more than one char actually has type int, which has an implementation defined value.

If you're using C++ though, you're better off using std::string instead, as Mark B has suggested:

#include <iostream> 
#include <string> 
int main(){ 
    std::string filename;
    std::cout << "Type in the filename: "; 
    std::cin >> filename; 
    filename += ".txt"; 
    std::cout << filename; 
} 

Upvotes: 15

Elf King
Elf King

Reputation: 1183

strcat second argument uses a string (double quotes). You are using single quotes (character == integer )

Ahmed

Upvotes: 2

Mark B
Mark B

Reputation: 96241

" and ' mean different things in C++. The single quote means a character, while the double quote means a C-string. You should use ".txt".

Given that this is C++ however, don't use C-style char[] at all: Use std::string instead:

#include <iostream>
#include <string>
int main(){
    std::string filename;
    cout << "Type in the filename: ";
    cin >> filename;
    filename += ".txt";
    cout << filename;
}

Upvotes: 8

Related Questions