字符串及其头文件有问题

Having problems with string and its header files

#include <iostream>
#include <cstring> //which one should I use...out of these three header files
#include <string>  //whats difference in each of them
#include <string.h>
int main()
{
    std::string first_name;
    std::string second_name;

    std::cout << "\n First name : ";
    std::cin >> first_name;

    std::cout << "\n Second name : ";
    std::cin >> second_name;

    strcat(first_name," ");         //not working
    strcat(first_name,second_name); //not working

    std::cout << first_name;
    return 0;
}

我之前用 c++ strcat(字符串连接)编写过程序。我遵循了新的教程和新的 IDE 编译器(其中包含新的数据类型,即 'string' )。当我尝试使用它时,它会给我错误。

ERROR:- ||=== Build: Debug in string1 (compiler: GNU GCC Compiler) ===| C:\Users\Admin\Desktop\c++ projects\string1\main.cpp||In function 'int main()':|
C:\Users\Admin\Desktop\c++ projects\string1\main.cpp|16|error: cannot convert 'std::string {aka std::basic_string}' to 'char*' for argument '1' to 'char* strcat(char*, const char*)'|
C:\Users\Admin\Desktop\c++ projects\string1\main.cpp|17|error: cannot convert 'std::string {aka std::basic_string}' to 'char*' for argument '1' to 'char* strcat(char*, const char*)'|
||=== Build failed: 2 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

strcat 是使用字符串的 old-style(我的意思当然是 char*)。

现在只需 #include<string> 即可轻松使用 std::string:

std::string name = "Foo";
std::string lastName = "Bar";
std::string fullname = name+" "+lastName;
std::cout << fullname ; // <- "Foo Bar"

更多: (@michael-krelin-hacker)

<string><string.h>是两个不同的headers:

  • <string> 适用于 C++ std::string class
  • <string.h> 用于 c 字符串函数(如 strlen() 等),对于 c++ 项目应该是 <cstring>(这是第三个,你不知道的).

More2:如果你更喜欢使用 C 风格,试试这个:

std::string name = "Foo";
std::string lastName = "Bar";
///
int len = name.length();
char* fullname = new char[len+1];
strncpy(fullname, name.c_str(), name.length());
fullname[len]='[=11=]';
///
strncat(fullname," ", 1);
strncat(fullname,lastName.c_str(), lastName.length());
///
std::cout<<fullname;