C/C++获取输入时的回车问题

这篇博客探讨了在C/C++编程中处理输入时遇到的回车问题。通过示例代码展示了如何使用`gets()`和`scanf()`函数读取字符串,并确保在后续输入时不包含回车符。此外,还介绍了一个名为`leftshift`的函数,用于将字符串左移指定次数,以及在读取用户输入时如何处理非正数的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <malloc.h>

using namespace std;
void leftshift(char*a, int n, int m);

int main()
{
    char q = 0;
    do{
        char *a = (char *)malloc(20*sizeof(char));
        memset(a,0,20);
        int num = 0;
        int times = 0;
        if(q != 0)
            getchar();
//        cout << "Please input the string!" << endl;
        printf("Please input the string\n");
        gets(a);
        while(a[num] != 0)
        {
            printf("%c %d\n",a[num],num);
            num++;

        }
    //    while(scanf("%c",a+num) && a[num] != "\0")
    //    {
    //        num++;
    //    }
        cout << "The length of the input string " << num << endl;
        cout << "Please input the number you want to shift!" << endl;
        while(scanf("%d",×) && times <= 0)
        {
            //接受完输入后,下次再获取时,需要先将回车键获取,以免下次获取的内容中含回车键
            printf("Please input a positive number!\n");
            //标准输出中的回车键跟这个不相关
        }
        leftshift(a,num,times);
        printf("After shift: %s\n",a);
        free(a);
        printf("Continue?y:n\n");
        getchar();  //之前有scanf获取输入,故此处先将回车获取
//        do{
//            scanf("%c",&q);
//        }while(q!='y' || q!='n');
        scanf("%c",&q);

    }while(q=='y');
    return 0;
}


void leftshift(char*a,int n,int m)
{
    while(m--)
    {
        char tmp = a[0];
        for(int i = 1; i <= n; i++)
        {
            a[i-1] = a[i];
        }
        a[n-1] = tmp;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值