修复下面代码#include<iostream> using namespace std; void Show() { printf("请输入想选择的指令:\n"); printf("1.显示串\n"); printf("2.显示串长\n"); printf("3.两串做比较\n"); printf("4.求子串\n"); printf("5.定位\n"); printf("0.退出\n"); printf("-------------------\n"); } int main() { int n; Show(); scanf("%d", &n); char s[15] = "qwertasdfzxc"; HString S; StrAssign(S, s); char t[5] = "asdf"; HString T; StrAssign(T, t); HString Sub; while (n != 0) { switch (n) { case 1: printf("第一个串为:%s\n", S.ch); printf("第二个串为:%s\n", T.ch); break; case 2: printf("第一条串长:%d\n", StrLength(S)); printf("第二条串长:%d\n", StrLength(T)); break; case 3: int n; n = StrCompare(S, T); if (n != 0) if (n > 0) printf("前面长\n"); else printf("后面长\n"); else printf("一样长\n"); break; case 4:printf("请输入你想取的位置及长度:\t"); int j, l; scanf("%d %d", &j, &l); SubString(Sub, S, j, l); StrPrint(Sub); break; case 5: int k; printf("输入查询的位置:\n"); scanf("%d", &k); int x = Index(S, T, k); printf("定位到的位置为:%d", x); break; } printf("\n"); Show(); scanf("%d", &n); } return 0; }
时间: 2023-07-13 15:17:48 浏览: 150
修复后的代码如下:
```
#include<iostream>
using namespace std;
void Show() {
cout << "请输入想选择的指令:" << endl;
cout << "1.显示串" << endl;
cout << "2.显示串长" << endl;
cout << "3.两串做比较" << endl;
cout << "4.求子串" << endl;
cout << "5.定位" << endl;
cout << "0.退出" << endl;
cout << "-------------------" << endl;
}
int main() {
int n;
Show();
cin >> n;
char s[15] = "qwertasdfzxc";
HString S;
StrAssign(S, s);
char t[5] = "asdf";
HString T;
StrAssign(T, t);
HString Sub;
while (n != 0) {
switch (n) {
case 1:
cout << "第一个串为:" << S.ch << endl;
cout << "第二个串为:" << T.ch << endl;
break;
case 2:
cout << "第一条串长:" << StrLength(S) << endl;
cout << "第二条串长:" << StrLength(T) << endl;
break;
case 3:
int res;
res = StrCompare(S, T);
if (res != 0) {
if (res > 0) {
cout << "前面长" << endl;
} else {
cout << "后面长" << endl;
}
} else {
cout << "一样长" << endl;
}
break;
case 4:
cout << "请输入你想取的位置及长度:" << endl;
int j, l;
cin >> j >> l;
SubString(Sub, S, j, l);
StrPrint(Sub);
break;
case 5:
int k;
cout << "输入查询的位置:" << endl;
cin >> k;
int x = Index(S, T, k);
cout << "定位到的位置为:" << x << endl;
break;
default:
cout << "错误的指令" << endl;
break;
}
Show();
cin >> n;
}
return 0;
}
```
主要的改动如下:
1. 将 printf 改为 cout,将 scanf 改为 cin;
2. case 3 中定义的变量 n 与 main 函数中定义的变量 n 冲突,改为 res;
3. 增加了 default 分支,用于处理错误的指令。
阅读全文