简体   繁体   English

帮助在指定位置的字符串中插入单词

[英]help in inserting a word in a string at position specified

I made a code that would insert a word entered by the user in a string at specified position.for example if string is :alice wonderland,word is in and pos is 6,op/ should be: alicein wonderland But,the code isn't working.Can u tell me the flaws? 我编写了一个代码,该代码可以在指定位置的字符串中插入用户输入的单词。例如,如果字符串是:alice wonderland,单词in,而pos是6,op /应该是:alicein wonderland但是,代码是“不行。你能告诉我缺点吗? here's the code: 这是代码:

#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();
}

Your code, as provided, will not compile. 您提供的代码将无法编译。 Are you having issues compiling the code? 您在编译代码时遇到问题吗? I'll ignore the syntax errors and point out the logic errors. 我将忽略语法错误,并指出逻辑错误。 Change the third for loop into 将第三个for循环更改为

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

Change the fourth for loop to 将第四个for循环更改为

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

Lastly, change the str[len+w-1]='\\0'; 最后,更改str[len+w-1]='\\0'; to str[len+w]='\\0'; str[len+w]='\\0'; The logic errors with your code are essentially an "off by one" error. 您的代码的逻辑错误本质上是“一对一的”错误。 In each case, removing the -1 should fix the errors. 在每种情况下,删除-1都可以修复错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM