考研算法38天:反序输出 【字符串的翻转】

题目

题目收获

很简单的一道题,但是还是有收获的,我发现我连scanf的字符串输入都忘记咋用了。。。。。我一开始写的

cpp 复制代码
#include <iostream>
#include <cstring> 
using namespace std;

void deserve(string &str){
	int n = str.size();
	int Size = n/2;
    for(int i=0;i<Size;i++){
        swap(str[i],str[n-1-i]);
    }
}

int main(){
    string str;
    while(scanf("%s",&str)!=EOF){
        deserve(str);
        printf("%s",str);
    }
    return 0;
}

结果发现咋搞都编译错误,查别人的博客发现别人和自己一样,最后就问了chat果然是自己记错了。。。。。。

cpp 复制代码
#include <iostream>
#include <cstring>
using namespace std;

void reverse(char *str) {
    int n = strlen(str);
    int Size = n / 2;
    for (int i = 0; i < Size; i++) {
        swap(str[i], str[n - 1 - i]);
    }
}

int main() {
    char str[100];  // Assuming a maximum length of 100 characters
//输入不需要&这个符号
    while (scanf("%s", str) != EOF) {
        reverse(str);
        printf("%s ", str);
    }
    return 0;
}

好吧,哈哈哈哈哈。

AC代码

cpp 复制代码
#include <iostream>
#include <cstring> 
using namespace std;

void deserve(string &str){
	int n = str.size();
	int Size = n/2;
    for(int i=0;i<Size;i++){
        swap(str[i],str[n-1-i]);
    }
}

int main(){
    string str;
    while(cin>>str){
        deserve(str);
        cout<<str<<endl;
    }
    return 0;
}

事实证明scanf和printf是要比cin和cout快的。

相关推荐
tryCbest11 小时前
软考 - 排序算法
算法·排序算法
念恒1230612 小时前
基础IO(文件缓冲区)
linux·c语言·c++
AKA__Zas12 小时前
芝士算法(双指针篇 1.0)
java·算法·学习方法
吃着火锅x唱着歌12 小时前
LeetCode 726.原子的数量
linux·算法·leetcode
君义_noip12 小时前
CSP-S 2025 提高级 第一轮(初赛) 阅读程序(3)
c++·算法·信息学奥赛·csp-s 初赛
玛卡巴卡ldf12 小时前
【LeetCode 手撕算法】(栈)有效括号、最小栈、字符串解码、每日温度、柱状图最大矩形
java·数据结构·算法·leetcode·力扣
happyprince12 小时前
05-FlagEmbedding 评估模块详解
算法
wuweijianlove12 小时前
算法优化的多目标平衡与性能建模研究的技术7
算法
汉克老师12 小时前
GESP6级C++考试语法知识(三、图与树(三))
c++·中序遍历·bst·完全二叉树·二叉排序树·gesp6级·gesp六级
_深海凉_12 小时前
LeetCode热题100-两两交换链表中的节点
算法·leetcode·链表