String 初学者:c++;代码:打印时字符串被复制
所以我编写了一个程序,在其中输入“n”个字符串。Porgram按字母顺序打印第一个和最后一个字符串,然后打印其余字符串(其余字符串没有字母顺序) 例如,用户输入String 初学者:c++;代码:打印时字符串被复制,string,for-loop,vector,String,For Loop,Vector,所以我编写了一个程序,在其中输入“n”个字符串。Porgram按字母顺序打印第一个和最后一个字符串,然后打印其余字符串(其余字符串没有字母顺序) 例如,用户输入 ab cd ef gh 计划应包括: ab gh cd ef 上面这部分在我的代码中工作得很好,问题是当你输入两次相同的字符串时,它会同时打印它们,这是不应该发生的。。。它应该跳过重复项并执行其原始工作 例如,如果我在代码中输入: ab cd ef gh ab 程序将打印两次ab等 ab ab cd
ab
cd
ef
gh
计划应包括:
ab
gh
cd
ef
上面这部分在我的代码中工作得很好,问题是当你输入两次相同的字符串时,它会同时打印它们,这是不应该发生的。。。它应该跳过重复项并执行其原始工作
例如,如果我在代码中输入:
ab
cd
ef
gh
ab
程序将打印两次ab等
ab
ab
cd
ef
gh
代码如下:
#include<iostream>
#include<vector>
#include<string>
using namespace std;
int main(){
cout<<"Enter a number of words: ";
int n;
cin>>n;
vector<string> v;
for(int i=0;i<n;i++){
string temp;
cout<<"Enter "<<i+1<<". word: ";
cin>>temp;
v.push_back(temp);
}
if(v[0][0]<v[n-1][0])cout<<v[0]<<endl<<v[n-1];
else cout<<v[n-1]<<endl<<v[0];
cout<<endl;
for(int i=1;i<n-1;i++){
cout<<v[i]<<endl;
}
return 0;
}
#包括
#包括
#包括
使用名称空间std;
int main(){
coutn;
向量v;
对于(int i=0;i如果您不希望数组中有多个元素,您应该在每次添加字符串时检查它是否已经存在(在循环中,与所有其他字符串进行比较),或者您可以将容器从向量更改为另一个确保唯一性的容器,如或
使用向量,您可以如下更改代码:
#include<iostream>
#include<vector>
#include<string>
using namespace std;
int main() {
cout << "Enter a number of words: ";
int n;
cin >> n;
vector<string> v;
for( int i = 0; i < n; ) {
string temp;
cout << "Enter " << i + 1 << ". word: ";
cin >> temp;
// loop through the vector searching for temp
int j = 0;
while ( j < v.size() && v[j] != temp )
++j;
// add temp if it isn't already present
if ( j == v.size() ) {
v.push_back(temp);
++i;
}
else
cout << temp << " is already present\n";
}
// use the real size of the vector
int last = v.size() - 1;
if ( v[0][0] < v[last][0] )
cout << v[0] << endl << v[last];
else
cout << v[last] <<endl <<v[0];
cout << endl;
for ( int i = 1; i < last; i++ ){
cout << v[i] << endl;
}
return 0;
}
#包括
#包括
#包括
使用名称空间std;
int main(){
cout>n;
向量v;
对于(int i=0;i cout@noobcoder你是什么意思?我的答案应该有助于解决你问题中所述的问题。试试我的代码,看看它是否如你预期的那样工作。你不必更改你的问题,如果我的答案有帮助,你发现它很有用,你就可以投票或回答。我试过了,程序崩溃了,我有代码,我只是希望有人修复它并解释它们是怎么做的。@noobcoder现在就试试。如果是重复的,你可以要求另一个词,也可以不要求,但我忘了在输入后添加计算向量实际大小的代码。即使程序应该在输入后删除重复项并继续原来的工作,你在这里做了一件好事,谢谢。删除输入部分并相反,以编程方式插入数据以接近最小的示例。也就是说,程序到底在什么时候出错?学习使用调试器或使用输出语句来查找该点。然后,错误出现在前一行。