代码题不会,c语言,考指针

img


改代码太煎熬了我发现我很多地方都错了,总是有这个警告,很离谱……


#include <iostream>
#include <iostream>
using namespace std;
int main()
{
    char s,s2;
    int m,j=0;
    string s1;
    cout << "请输入一个数据:" << endl;
    cin >> s1;
    cout << "请输入m个位置:" << endl;
    cin >> m;
    for (int i = 0; i <m; i++)
    {
        j--;
        s = s1[i];
        s1[i] = s1[s1.length() +j];
        s1[s1.length() + j] = s;
    }
    int k,o=0;
    for (k = s1.length() - m; k < s1.length(); k++)
    {
        o--;
        s2 = s1[k];
        s1[k] = s1[s1.length() -1];
        s1[s1.length() -1] = s2;

    }
    for (int i = 0; i < s1.length()-m; i++)
    {
        cout << s1[i] << " ";
    }
    for (k = s1.length() - m; k < s1.length(); k++)
    {
        cout << s1[k] << " ";

    }
}

自己写的贴出来看看

C语言代码参考如下:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
    // 定义长度为100的字符串
    char str[100];
    int m;
    printf("Please input the string:");
    scanf("%s", str);
    printf("Please input the number of swap-char:");
    scanf("%d", &m);
    // 获取字符串实际长度
    int len = (int)strlen(str);
    char t;
    // 前m个逆序
    for (int i = 0; i < m / 2; i++) {
        t = str[i];
        str[i] = str[m - 1 - i];
        str[m - 1 - i] = t;
    }
    // 前后m个换位
    for (int i = 0; i < m; i++) {
        t = str[i];
        str[i] = str[len - 1 - i];
        str[len - 1 - i] = t;
    }
    printf("The new string is %s\n", str);
    return 0;
}