C++string,char* 字符數組,int類型之間的轉換


string、int 常見類型之間相互轉換

int & string 之間的轉換

  • C++中更多的是使用流對象來實現類型轉換

針對流對象 sstream實現

int,float 類型都可以實現

#include <sstream>
//int convert to string
void int2str(const int &int_temp,string &string_temp){
    stringstream s_stream;
    s_stream<<int_temp;
    string_temp=s_stream.str();
    //s_stream>>string_temp;  // 也可以實現
}

//string convert to int
void str2int(const string &string_temp,int &int_temp){
    stringstream s_stream(string_temp);
    s_stream>>int_temp;  
}
  • 其他的方法

c_str()函數

string.c_str() 可以將string字符串轉換成一個指向與string相同字符數組的頭指針

// atoi
void str2int(string &string_temp,int &int_temp){
    int_temp=atoi(string_temp.c_str());
}

// stoi實現
void str2int_stoi_version(string& string_temp,int &int_temp){
    int_temp=stoi(string_temp);
}

字符數組char* 與string之間的轉換

  • 字符數組轉為string
char ch [] = "ABCDEFGHIJKL";
string str(ch);//也可string str = ch;

// other way

char ch [] = "ABCDEFGHIJKL";
string str;
str = ch;//在原有基礎上添加可以用str += ch;
  • string轉為字符數組
char buf[8];
string str("ABCDEFG");
length = str.copy(buf,8);     //str.copy() return number of character copied
buf[length] = '\0';   //末尾置0


char buf[8];
string str("ABCDEFG");
strcpy(buf, str.c_str());//strncpy(buf, str.c_str(), 8);

strcpy()函數

//char* strcpy( char* dest, const char* src );
#include <iostream>
#include <cstring>
#include <memory>
int main()
{
    const char* src = "Take the test.";
//  src[0] = 'M'; // can't modify string literal
    auto dst = std::make_unique<char[]>(std::strlen(src)+1); // +1 for the null terminator
    std::strcpy(dst.get(), src);
    dst[0] = 'M';
    std::cout << src << '\n' << dst.get() << '\n';
}
// Take the test.
// Make the test.

strncpy()函數

// char *strncpy( char *dest, const char *src, std::size_t count );

#include <iostream>
#include <cstring>
int main()
{
    const char* src = "hi";
    char dest[6] = {'a', 'b', 'c', 'd', 'e', 'f'};
    std::strncpy(dest, src, 5);
 
    std::cout << "The contents of dest are: ";
    for (char c : dest) {
        if (c) {
            std::cout << c << ' ';
        } else {
            std::cout << "\\0" << ' ';
        }
    }
    std::cout << '\n';
}
//The contents of dest are: h i \0 \0 \0 f

int 和 char

int a=1;
char c=a+'0'; //c的值就是'1'的ASCII碼值


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM