String & Cstring

Task

Implement the two functions which proceed to exchange between string and cstring.
(1) std::string change1(const char* cstr);

Convert a string of the cstring type to one belonging to the string type.
(2) void change2(std::string str, char* cstr);

Convert a string of the string type to one belonging to the cstring type.
main()函数


#include <cstdio>
#include <iostream>
#include "exchange.h"

std::string str;
char cstr[100];
int main() {
    std::cin >> str;
    change2(str, cstr);
    puts(cstr);
    scanf("%s", cstr);
    std::cout << change1(cstr) << std::endl;
    return 0;
}
解答:
#include<string>
#include<iostream>
using namespace std;
void change2(string &str, char *cstr)
{
    int i=0;
    for(i=0;i<str.length();++i)
    {
        cstr[i]=str[i];
    }
    cstr[i]='\0';
}
string change1(char *cs)
{
    string str = cs;
    return str;
}

心得:
(1)千万不要让了给字符串数组的结尾加上结束符!!!!很重要!!!

猜你喜欢

转载自blog.csdn.net/Liusyu6688/article/details/80638801
今日推荐