#include<bits/stdc++.h> using namespace std; string a; int main() { getline(cin,a); for(int i=0;i<=a.size();i++) { if(a[i]=='(') { while(a[i]!=')') { i++; } continue; } else { cout<<a[i]; } } }为何WA
时间: 2024-03-22 08:37:28 浏览: 32
这段代码的问题在于第7行的循环条件是 `i<=a.size()`,应该改为 `i<a.size()`,否则会多读取一次字符串 `a` 的最后一个字符,导致越界。同时,第4行应该加上判断条件 `if(i==a.size()) break;`,以防止在最后一个字符是左括号时出现无限循环的情况。修改后的代码如下:
```c++
#include<bits/stdc++.h>
using namespace std;
string a;
int main() {
getline(cin,a);
for(int i=0;i<a.size();i++) {
if(a[i]=='(') {
while(a[i]!=')') {
i++;
if(i==a.size()) break;
}
continue;
}
else {
cout<<a[i];
}
}
}
```
相关问题
#include <bits/stdc++.h> using namespace std; typedef struct{ string s; }tree[101]; int main() { int n; cin>>n; for(int i=1;i<=n;i++){ cin>>tree[i].s; getline(cin,s); } int a[101]={1}; for(int i=1;i<=n;i++){ for(int j=i+1;j<=n;j++){ if(str[j]==str[i]){ a[j]++; } } } for(int i=1;i<=n;i++){ cout<<a[i]<<endl; } return 0; }为什么不对呢
这段代码存在一些问题,导致编译错误。首先,你在定义结构体时使用了一个未定义的类型 `string`,应该包含头文件 `<string>` 来解决这个问题。另外,在输入循环中你使用了 `getline(cin, s)`,但是你并没有定义变量 `s`,应该改为 `getline(cin, tree[i].s)`。此外,比较字符串是否相等时,应该使用 `tree[j].s == tree[i].s` 而不是 `str[j] == str[i]`。最后,你输出的数组应该是 `a` 而不是 `str`。下面是修改后的代码:
```cpp
#include <bits/stdc++.h>
using namespace std;
typedef struct {
string s;
} tree[101];
int main()
{
int n;
cin >> n;
cin.ignore(); // 忽略换行符
for (int i = 1; i <= n; i++) {
getline(cin, tree[i].s);
}
int a[101] = { 0 }; // 初始化为0
for (int i = 1; i <= n; i++) {
for (int j = i + 1; j <= n; j++) {
if (tree[j].s == tree[i].s) {
a[j]++;
}
}
}
for (int i = 1; i <= n; i++) {
cout << a[i] << endl;
}
return 0;
}
```
这样修改后,代码应该可以正常编译和运行。
#include<bits/stdc++.h> using namespace std; int main(){ int a[26]; string s,s1,s2,s3; getline(cin,s1); getline(cin,s2); s = s1+s2; s3 = ""; for(int i = 0;i<s.length();i++){ if(a[s[i]] == 0) { s3 =s3+s[i]; a[s[i]] = 1; } } cout<<s3; return 0; }c++中利用这个代码将输入的两个字符串按顺序拼接的同时不出现重复字符有什么问题
这个代码有以下问题:
1. `a` 数组没有初始化,会导致数组中的元素值是不确定的,应该将其初始化为 0。
2. 在判断字符是否出现过时,应该使用字符的 ASCII 码作为数组下标,而不是字符本身。
3. 对于字符串中的空格和其他特殊字符,也会被计入,可能会导致输出结果出错。
4. 当输入的字符串中包含多个相同的字符时,只会输出一个,而不是全部输出。
修正后的代码如下所示:
```c++
#include<bits/stdc++.h>
using namespace std;
int main(){
int a[128] = {0}; // 初始化数组
string s,s1,s2,s3;
getline(cin,s1);
getline(cin,s2);
s = s1+s2;
s3 = "";
for(int i = 0;i<s.length();i++){
if(a[int(s[i])] == 0 && isalpha(s[i])) { // 使用 ASCII 码作为数组下标,并且判断是否为字母
s3 = s3 + s[i];
a[int(s[i])] = 1;
}
}
cout<<s3;
return 0;
}
```
其中,`isalpha()` 函数用于判断字符是否为字母。