简体   繁体   中英

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

替代文字

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; 
} 

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

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

Ahmed

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM