首页 文章

遇到字符串及其头文件的问题

提问于
浏览
-1
#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(string catenation)上完成了程序 . 我遵循了新的教程和新的IDE编译器(包含新的数据类型即'string') . 当我尝试使用它时,它给了我错误 .

错误: - || === Build:在string1中调试(编译器:GNU GCC编译器)=== | C:\ Users \ Admin \ Desktop \ c projects \ string1 \ main.cpp ||在函数'int main()'中: C:\ Users \ Admin \ Desktop \ c projects \ string1 \ main.cpp | 16 | error:无法将'std :: string '转换为'char *'以将参数'1'转换为'char * strcat(char *,const char *)'| C:\ Users \ Admin \ Desktop \ c projects \ string1 \ main.cpp | 17 | error:无法将'std :: string '转换为'char *'以将参数'1'转换为'char * strcat(char *,const char *)'| || ===构建失败:2个错误,0个警告(0分钟,0秒(秒))=== |

1 回答

  • 1

    strcat 是使用字符串的旧式(当然我的意思是 char* ) .

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

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

    More :(@ michael-krelin-hacker)

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

    • <string> 适用于c std::string

    • <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]='\0';
    ///
    strncat(fullname," ", 1);
    strncat(fullname,lastName.c_str(), lastName.length());
    ///
    std::cout<<fullname;
    

相关问题