2015-06-19 53 views
0

你好,我想讀的輸入和增加每個字符的字符串的左側,例如:寫入字符串到左用C

我所做的輸入1,輸出應該是:

1 

然後我想添加的號碼2:輸出應該是:

21 

然後我想添加的號碼3:輸出應該是:

321 

然後我要添加的數量4:輸出應爲:

4321 

等...

到目前爲止我已成功的情況下串長度= 0和1:

if(stringLength == 1){ 
    string[ stringLength++ ] = string[ 0 ]; 
    string[ pStringLength - 1 ] = input; 
} 
else if(stringLength == 0) 
    string[ stringLength++] = input; 

我的問題是在stringLength> 2:

if(stringLength >= 2){ 
    for(indexx = 1; indexx < stringLength; indexx++){ 
     string[ stringLength++ ] = string[ stringLength - indexx ]; 
    } 
    string[ 0 ] = input; 
} 

上面的代碼給我分段錯誤,在此先感謝您的幫助! 編輯!!:

if(stringLength >= 2){ 
    for(indexx = 1; indexx < stringLength; indexx++){ 
     string[ stringLength ] = string[ stringLength - indexx ]; 
    } 
    stringLength++; 
    string[ 0 ] = input; 
} 

現在輸出始終限制在2:

如果我有:

21 

,我嘗試添加 '3':

32 

'1'被刪除,剛剛離開最後2個輸入...

+0

string [stringLength ++]正在使循環無限 – aa1992

回答

3
string[ stringLength ] = string[ stringLength - indexx ]; 

上面的語句不斷將overwritting相同index.Thats爲什麼輸出被限制爲2個位數。

提示:您需要將元素從結尾開始向右推一個位置,以便最後覆蓋字符串[0]。

假設陣列是{1,2,3,4}和我要添加5所以輸出應該是{5,1,2,3,4}

然後由每個元件移動到右從最後一個位置將使數組{1,1,2,3,4},然後你可以做數組[0] = 5;

移動可以通過這種方式

for(i=arr.length-1;i>=1;i--) 
{ 
    arr[i]=arr[i-1]; 
} 

希望它可以幫助來完成。

+0

謝謝兄弟!我必須對該代碼進行的唯一修改是針對(i = arr.length; i> = 1; i--)(i = arr.length-1; i> = 1; i--)我非常感謝你的幫助! – Javi9207

3

如果在循環內部增加stringLength,則循環永遠不會結束,因爲循環條件檢查stringLength的值。

+0

我看不到這些! – Javi9207

1

看看下面的代碼。

#include <stdio.h> 
int main() 
{ 
    char a[10] = ""; 
    int i = sizeof(a)-2; 
    while(i>=0) 
    { 
     scanf(" %c",&a[i]); 
     printf("%s\n",a+i); 
     i--; 
    } 
    return 0; 
} 

我遵守了我的數組大小10是高達你來決定數組的大小。

輸出:

1 
1 
2 
21 
3 
321 
4 
4321 
5 
54321 
6 
654321 
7 
7654321 
8 
87654321 
9 
987654321 
+0

對不起兄弟,我不能將你的代碼添加到我的代碼中,謝謝你的關注!我已經嘗試了另一種螞蟻,它爲我工作! – Javi9207