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

时间:2015-01-11 07:34:23

标签: c++ string char codeblocks

#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 {aka std :: basic_string}'转换为'char *'以将参数'1'转换为'char * strcat(char *,const char *)'|
      C:\ Users \ Admin \ Desktop \ c ++ projects \ string1 \ main.cpp | 17 | error:无法将'std :: string {aka std :: basic_string}'转换为'char *'以将参数'1'转换为'char * strcat(char *,const char *)'|
      || ===构建失败:2个错误,0个警告(0分钟,0秒(秒))=== |

1 个答案:

答案 0 :(得分: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"

更多 :( @ michael-krelin-hacker)

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

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