Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
198 views
in Technique[技术] by (71.8m points)

begin the string in C

#include<stdio.h>
#include<string.h>
int main()
{
    char a[50];
    printf("nhap chuoi : ");
    gets(a);

    //cat cac ki tu trang cuoi chuoi
    for (int i= strlen(a)-1;i>=0;i--)
    {
        if(a[i]!=' ')
        {
            a[i+1]='';
        }
        break;
    }
    //cat cac ki tu trang dau chuoi
    for(int i=0; i<strlen(a); i++)
    {
        if(a[i]==' '&& a[i+1]!=' ');
        strcpy(a,a[i+1]);
    }
    printf("
chuoi sau khi cat:");
    puts(a);
    return 0;
}//main

When I run program, it shows this error in line 17:

[Error] invalid conversion from 'char' to 'const char*' [-fpermissive].

question from:https://stackoverflow.com/questions/65930872/begin-the-string-in-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This:

if(a[i]==' '&& a[i+1]!=' ');
strcpy(a,a[i+1]);

does not make sense. First the semicolon after the if statement makes it a no-op. And the strcpy is also incorrect.

I guess you want to strip out a single character and thus wanted to write strcpy(a, &a[i+1]). That second parameter needs to be a pointer (a[i+1] is a char) That is however invalid as the source and destination overlap.

for possibly overlapping memory you need to use memmove, but there you have to specify the number of bytes to move (and not forget the terminating zero): memmove(a, &a[i+1], strlen(a)-i)

(the number of chars to copy is strlen(a)-(i+1) and we need to add one for the terminating zero)

So that code becomes:

if(a[i]==' '&& a[i+1]!=' ') {
    memmove(a, &a[i+1], strlen(a)-i);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...