C++中數字與字符串之間的轉換 scanf string總結(復習必讀)


 

   1 string的scanf讀入操作

C++里面控制台輸入直接使用cin操作就可以了;或者getline(istringstream,string);

字符和數字加減就是字符的ASCII碼和數字直接加減。

只有內置類型int,float,char,double,bool可以直接賦值,scanf讀入string不能直接使用scanf直接賦值,因為string是一個類class,有專門的初始化函數,不能使用scanf,同理gets接收的也是一個char指針。編程語言自帶的sizeof也是一樣,不能對string進行直接操作。

string s;
s.resize(100);
scanf("%s",&s[0]);

或者:

string s;
char *c = new char(100);
scanf("%s",c);//scanf("%s",&c[0]);
s = c;//給首地址

strlen是得到輸入的有效字符串,而不是開辟的空間大小100.

strlen所作的僅僅是一個計數器的工作,它從內存的某個位置(可以是字符串開頭,中間某個位置,甚至是某個不確定的內存區域)開始掃描,直到碰到第一個字符串結束符'\0'為止,然后返回計數器值。--就是指實際字符串或字符數組的實際長度(不是所占空間的字節數)。

char A[6]={'a','b','\0','d','e','r'}; 
int i=strlen(A);          //i為2,因為到’\0’結束,故實際A[]只有2個元素 
sizeof()
string s;
char *c = new char(100);
scanf("%s",c);
int len  = strlen(c);
s1.resize(len);//動態編譯
s1.assign(c,c + len);//copy(c,c + len,s1.begin());針對其他結構 
class X 
  
  int i; 
  int j; 
  char k; 
  }; 
  X x; 
cout<<sizeof(X)<<endl; 結果 12 ===》內存補齊 
cout<<sizeof(x)<<endl; 結果 12 同上 
解釋一下,在class X中,成員中最大的所占的空間為int類型所占的空間4個字節,故內存補齊,最后結果為: ((int)(實際成員所占內存空間的和/4)+1)*4

*所以不能通過sizeof(string) / sizeof(string[0])得到實際char元素個數,不管string等於多少,最后的結果都是28;因為string是一個class。

copy()用法:

此算法接收三個迭代器iterator,前兩個表示一個輸入范圍,第三個表示目的序列的起始位置。

char 和int 的轉換:

int = char - '0';

char = int + '0';

 

2 C++中數字與字符串之間的轉換(important)

 

 1、字符串數字之間的轉換

(1)string --> char *
   string str("OK");
   const char * p = str.c_str();

(2)char * -->string
   char *p = "OK";
   string str(p); 
(3)string->double
  double d=atof(s.c_str());

常用函數atoi(),itoa(),to_string();


2、數字轉字符串:使用sprintf()函數

char str[10];
int a=1234321;
sprintf(str,"%d",a);
--------------------
char str[10];
double a=123.321;
sprintf(str,"%.3lf",a);
--------------------
char str[10];
int a=175;
sprintf(str,"%x",a);//10進制轉換成16進制,如果輸出大寫的字母是sprintf(str,"%X",a)
--------------------
char *itoa(int value, char* string, int radix); 
同樣也可以將數字轉字符串,不過itoa()這個函數是平台相關的(不是標准里的),故在這里不推薦使用這個函數。

3、字符串轉數字:使用sscanf()函數

char str[]="1234321";
int a;
sscanf(str,"%d",&a);
.............
char str[]="123.321";
double a;
sscanf(str,"%lf",&a);
.............
char str[]="AF";
int a;
sscanf(str,"%x",&a); //16進制轉換成10進制

另外也可以使用atoi(),atol(),atof().

4、使用stringstream類

用ostringstream對象寫一個字符串,類似於sprintf() 
  ostringstream s1;
  int i = 22;
  s1 << "Hello " << i << endl;
  string s2 = s1.str();
  cout << s2;

用istringstream對象讀一個字符串,類似於sscanf() 
  istringstream stream1;
  string string1 = "25";
  stream1.str(string1);
  int i;
  stream1 >> i;
  cout << i << endl;  // displays 25

 

3 string類的所有函數操作總結

 

1、初始化string

string s = "1234";
string s("1234");
string s(n,'c');
string s(s1,pos2);//s是s2從下標pos2開始的字符的拷貝
string s(s1,pos2,len2);//s是s2從下標pos2開始len2個字符的拷貝

2、string基本操作

2.1 輸入:以回車或者空格分開,或者文件末尾EOF;

cin >> s;
getline(cin,s); 
getline(istringstream,s);

2.2 c風格的string函數(下面的必須以'\0'結尾的字符串)

strlen(p);     //返回p的長度,不包含結尾‘\0’
strcmp(p1,p2); //p1 == p1 -> 返回0,p1 > p2 -> 返回正值,p1 < p2返回負值
strcat(p1,p2); // p1 + p2
strcpy(p1,p2);//p2拷貝給p1;

string s = "123";

const char *p = s.c_str();

3、 string作為順序容器的操作

//子字符串的操作:
s.substr(pos,n) ;//返回s中從pos開始的n個字符的子字符串
s.erase(pos,len);//刪除從pos開始的len個字符,len不寫的話刪除pos 開始的所有字符
s.insert(pos,args);從pos位置插入args
s.assign(args);//將s中的字符替換為args中的字符
s.append(args);
s.replace(range,args);//刪除range中的元素,替換為args中的元素
//args具體看primer P323

string的搜索操作:

s.find(args);
s.rfind(args);
s.find_first_of(args);
s.find_last_of(args);
s.find_first_not_of(args);
s.find_last_not_of(args);

 每個操作接收一個可選的第二參數,可以用來指定從什么位置開始搜索。例如args = c,pos,代表從pos位置開始搜索c,其中pos參數是可以省略的。

如果搜索失敗,則返回一個string::npos的static的成員。

s.find_first_of(args);在s中查找args中任何一個字符第一次出現的位置。

#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main() {
    string target("ad2c3d7r4e6");
    string numbers("0123456789");
    string num, alpha;
    unsigned int pos = 0;    
    while ( (pos = target.find_first_of(numbers,pos)) != string::npos) {
        num.push_back(target[pos]);
        ++pos;
    }
    pos = 0;
    while ( (pos = target.find_first_not_of(numbers, pos)) != string::npos) {
        alpha.push_back(target[pos]);
        ++pos;
    }
    cout << "numbers is :\n " << num << endl;
    cout << "alpha is :\n " << alpha << endl;
    system("pause");
    return 0;

}
void findLongestWord() {    
    ifstream in("input.txt");
    string res,tmp,source;
    string target("bdfghjklqpy");
    unsigned int pos = 0;
    int maxLen = 0;
    int resPos = 0;
    while (getline(in, tmp)) {
        istringstream ss(tmp);
        while (ss >> source) {
            if (pos = source.find_first_of(target, pos) != string::npos) {
                continue;
            }
            if (source.size() > maxLen) {
                maxLen = source.size();
                res = source;
            }
        }
    }
    cout << res << endl;

}

 compare函數:

根據s是等於、大於、小於參數指定的字符串,s.compare返回0,整數或負數。

數值轉換:

int i = 42;

string s = to_string(i);

int  i = stoi(s);//string轉換為int值。

 


免責聲明!

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



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