2010-03-19 54 views
22

我想製作一個程序,它會讀取字符串格式的一些數字並輸出,如下所示:如果數字是12345,它應該輸出12 23 34 45。我嘗試從C++字符串庫中使用substr()函數,但它給了我奇怪的結果 - 它輸出1 23 345 45而不是預期的結果。爲什麼?如何使用string.substr()函數?

#include <iostream> 
#include <string> 
#include <cstdlib> 
using namespace std; 
int main(void) 
{ 
    string a; 
    cin >> a; 
    string b; 
    int c; 

    for(int i=0;i<a.size()-1;++i) 
    { 
     b = a.substr(i,i+1); 
     c = atoi(b.c_str()); 
     cout << c << " "; 
    } 
    cout << endl; 
    return 0; 
} 
+1

[不應該使用'atoi'](http://stackoverflow.com/q/17710018/995714) – 2017-03-04 10:53:18

回答

44

如果我是正確的substr()第二個參數應該是串的長度。怎麼樣

b = a.substr(i,2); 

+1

是的,他每次增加子字符串的長度。 – 2010-03-19 14:08:20

+1

+1,觀察不錯! – 2010-03-19 16:38:00

16

如圖所示here,的第二個參數substr長度,不結束位置:

string substr (size_t pos = 0, size_t n = npos) const;

生成子串

返回與它的內容的字符串對象初始化爲當前對象的子字符串。該子字符串是從字符位置pos開始的字符序列,其長度爲n個字符。

你行b = a.substr(i,i+1);將產生,爲i值:

substr(0,1) = 1 
substr(1,2) = 23 
substr(2,3) = 345 
substr(3,4) = 45 (since your string stops there). 

你需要的是b = a.substr(i,2);

你也應該知道你的輸出就會看起來很有趣的數字,如12045。由於您在字符串部分使用了atoi()並輸出了該整數,因此您將得到12 20 4 45。你可能會想嘗試只是outputing字符串本身這是兩個字符長:

b = a.substr(i,2); 
cout << b << " "; 

事實上,整個事情可以更簡單地寫爲:

#include <iostream> 
#include <string> 
using namespace std; 
int main(void) { 
    string a; 
    cin >> a; 
    for (int i = 0; i < a.size() - 1; i++) 
     cout << a.substr(i,2) << " "; 
    cout << endl; 
    return 0; 
} 
2

另一個有趣的變形問題可以是:

你會如何做"12345""12 23 34 45"不使用另一個字符串?

下面會做什麼?

for(int i=0; i < a.size()-1; ++i) 
    { 
     //b = a.substr(i, 2); 
     c = atoi((a.substr(i, 2)).c_str()); 
     cout << c << " "; 
    } 
2

可以在c中使用以下代碼獲取上述輸出

#include<stdio.h> 
#include<conio.h> 
#include<string.h> 
int main() 
{ 
    char *str; 
    clrscr(); 
    printf("\n Enter the string"); 
    gets(str); 
    for(int i=0;i<strlen(str)-1;i++) 
    { 
    for(int j=i;j<=i+1;j++) 
     printf("%c",str[j]); 
    printf("\t"); 
    } 
    getch(); 
    return 0; 
} 
+0

這正是你不應該做的事情:http://powerfield-software.com/?p=829 – paxdiablo 2015-02-17 01:55:16

2

可能的解決方法,而無需使用substr()

#include<iostream> 
#include<string> 

using namespace std; 


int main() { 
    string c="12345"; 
    int p=0; 

    for(int i=0;i<c.length();i++) { 
     cout<<c[i]; 
     p++; 

     if (p % 2 == 0 && i != c.length()-1) { 
      cout<<" "<<c[i]; 
      p++; 
     } 
    } 
} 
2

SUBSTR(I,J)是指從索引開始我(假設第一個索引是0並且接下來的j個字符。 這並不意味着索引j。