全部是相同长度字符串为什么没有输出结果
时间: 2023-11-04 13:32:11 浏览: 42
如果全部输入的字符串长度相同,那么这段代码将输出任意一个输入的字符串,因为循环比较的时候只记录了最长字符串的内容,并没有记录最长字符串的位置。如果多个字符串长度相同,那么它们的内容都是最长的,但是只有最后一个字符串会被记录下来。
如果需要输出所有最长的字符串,可以修改代码如下:
```
#include<iostream>
#include<string>
#include<cstring>
#include<vector>
using namespace std;
int main(){
int N, max_len;
string str;
vector<string> max_str;
cout << "Input N and length: ";
cin >> N >> max_len;
for(int i=0; i<N; i++){
bool flag = false;
do{
cout << "Input string " << i+1 << ": ";
cin >> str;
if(str.length() > max_len){
cout << "The length of the string is too long, please input again." << endl;
flag = true;
}else{
flag = false;
}
}while(flag);
if(str.length() == max_len){
max_str.push_back(str);
}
}
if(max_str.size() == 0){
cout << "No string of maximum length." << endl;
}else{
cout << "The strings of maximum length are: ";
for(int i=0; i<max_str.size(); i++){
cout << max_str[i] << " ";
}
cout << endl;
}
return 0;
}
```
这段代码使用了 STL 中的 vector 类型,用来存储所有最长的字符串。在读入字符串时,如果字符串长度等于最大长度,则将该字符串添加到 vector 中。最后如果 vector 为空,则说明没有最长的字符串,否则输出所有最长的字符串。