用c++排序,得到一个空白输出

sorting in c++ giving me a blank output

本文关键字:一个 空白 输出 排序 c++      更新时间:2023-10-16

嗨,我正在尝试制作一个以和为输入的程序,比如说1+2+3+2+2+1,并且必须将和排序为1+1+2+2+2+3

这是代码

#include <iostream>
#include <algorithm>
#include <string.h>
using namespace std;
int main() {
    string s;
    char w[100];
    char x[100];
    cin>>s;
//moving string s to array w to remove the '+' charachter for sorting
for (int i=0; i>s.size() ;i++){
    if (s.at(i) = '+')continue;
    else s.at(i) == w[i];
}
//sorting array w
sort(w,w+100);
//moving array w to array x and re-adding the '+' after sorting
for (int y=0; y > s.size();y++){
    w[y]==x[y];
    x[y+1]=='+';
}
cout<<x;
return 0;

}

但当我运行它时,它会给我一个空白输出这是我第一次使用c++程序,我还是的初学者

感谢您的提前帮助!

我可以看出,您对该语言还很陌生,因为您对基本概念缺乏一些理解我会先给你一些关于错误的提示和解释,然后给你一个更合适的解决方案

首先,尽量避免像使用w和x那样使用C风格的数组。由于无边界检查,它们很容易出错,请考虑使用std::vector或std::array。

==和=不一样!==用于比较两个事物,=用于将右侧分配给左侧。

使用,您的循环完全错误

for (int i=0; i>s.size() ;i++)

甚至永远不会进入循环。使用i<s.size()。我还建议使用++I而不是I++,但这并不太重要。

你的"代码思维"有时也很奇怪

for (int i=0; i>s.size() ;i++){
    if (s.at(i) = '+')continue;
    else s.at(i) == w[i];
}

(不要在意>和=错误),为什么不检查它是否不是"+",而不是继续然后做一些事情?

该代码在逻辑上应该是

for (int i=0; i>s.size() ;i++){
    if (s.at(i) != '+') s.at(i) == w[i];
}

最后但同样重要的是,尽量保持一致。首先使用i作为循环变量,第二次使用y。这并不重要,但在编码时一致性总是很好的。

我为您的问题制定了一个快速解决方案:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;    
int main()
{
    string input;
    cin >> input;
    vector<int> nrs = vector<int>(); //initialising this is not really needed
    for (char c : input) //range based for loop, prevents mistakes with indices
    {
        if (c != '+')
        {
            nrs.push_back(c - '0'); // a char minus '0' gives the numerical value
        }
    }
    sort(nrs.begin(), nrs.end());
    string answer;
    for (int nr : nrs) //range based for loop again
    {
        answer += to_string(nr); //use to_string to convert an int to a string
        if (nr != nrs.back()) //to avoid adding the '+' after the last character
        {
            answer += '+';
        }
    }
    cout << answer << endl;
    return 0;
}