C/C++獲取輸入時的回車問題
阿新 • • 發佈:2019-02-06
#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; } }