2011-06-20 29 views
0

我做了一個代碼,用於在指定的位置插入用戶輸入的字符串。例如,如果字符串是:愛麗絲仙境,單詞在和pos是6 ,op /應該是:alicein仙境 但是,代碼不起作用。你能告訴我缺陷嗎? 下面的代碼:幫助在指定的位置插入字符串中的字符

#include<iostream.h> 
#include<conio.h> 
#include<stdio.h> 
void main() 
{ 
    char str[100],word[50]; 
    int i,len,p,f,w; 
    clrscr(); 
    cout<<"Enter string"<<endl; 
    gets(str); 
    cout<<"Enter word and position"<<endl; 
    gets(word); 
    cin>>p; 
    for(len=0;str[len!='\0';len++); 
    for(w=0;word[w]!='\0';w++); 
    for(i=len-1;i>=p-1;i--) 
     str[i+w]=str[i]; 
    for(i=p-1;f=0;f<w;f++,i++) 
     str[i]=word[f]; 
    str[len+w-1]='\0'; 
    cout<<"Modified string..."<<endl; 
    puts(str); 
    getch(); 
} 
+0

您應該開始使用C++風格。這意味着包括沒有擴展名的標題。例如。 '#include '和'#include '。你應該爲你的IO使用'cin','cout','getline()'等,而不是像'gets()'這樣的'stdio.h'。您應該在使用它們之前聲明變量,而不是在函數的開頭。此外,一些空格(空白行)和評論會很好,讓讀者的大腦休息一下。 –

+0

我會先解決你的編譯錯誤。 – aib

回答

0

你的代碼,如提供的,將無法編譯。你在編譯代碼時遇到問題嗎?我會忽略語法錯誤並指出邏輯錯誤。改變第三個for循環到

for(i=len-1;i>=p;i--) // note 'p-1' was changed to 'p' 
    str[i+w]=str[i]; 

更改第四for循環

for(i=p;f=0;f<w;f++,i++) // again, note the 'p-1' changed to 'p' 
    str[i]=word[f]; 

最後,改變str[len+w-1]='\0';str[len+w]='\0'; 你的代碼的邏輯錯誤本質上是一種「關閉的一個」錯誤。在每種情況下,刪除-1應該修復錯誤。