考研算法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快的。

相关推荐
lixinnnn.几秒前
C++: map和set
开发语言·c++
大袁同学9 分钟前
【二叉搜索树】:程序的“决策树”,排序数据的基石
数据结构·c++·算法·决策树·stl
郝学胜-神的一滴22 分钟前
Qt QPushButton 样式完全指南:从基础到高级实现
linux·开发语言·c++·qt·程序人生
⠀One0ne30 分钟前
【C++ 面试题】内存对齐
c++
蓝色汪洋31 分钟前
xtu oj环--唉
算法
Algo-hx34 分钟前
数据结构入门 (十):“左小右大”的秩序 —— 深入二叉搜索树
数据结构·算法
Elias不吃糖38 分钟前
NebulaChat 框架学习笔记:原子变量与左值引用的工程应用
c++·学习
Theliars1 小时前
Ubuntu 上使用 VSCode 调试 C++ (CMake 项目) 指南
c++·vscode·ubuntu·cmake
mjhcsp1 小时前
C++ map 容器:有序关联容器的深度解析与实战
开发语言·c++·map
将编程培养成爱好1 小时前
C++ 设计模式《账本事故:当备份被删光那天》
开发语言·c++·设计模式·备忘录模式