用c++排序,得到一个空白输出
sorting in c++ giving me a blank output
嗨,我正在尝试制作一个以和为输入的程序,比如说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;
}
相关文章:
- 如何创建一个程序来替换单个空白/选项卡的多个空白/选项卡
- 将QStringListModel包装在QABSTRACTITEMMODEL中,呈现一个空白列表
- QT子类UI表单显示一个空白窗口
- 字符串:: substr()返回一个空白字符串
- 我动态添加一个按钮,如何在Qt的另一个空白中使用此按钮
- 将QT QML应用程序部署到Windows上显示了一个空白窗口
- C 将数据读取到一个结构,但它跳过了我的一个获取线,使该元素空白
- 为什么这只会创建一个空白的输出文件
- OpenCV:试图创建一个空白图像,但核心已被转储
- 如何在C++中只从stdin/cin中读取一个空白
- Gtk::Window set_visible导致一个空白窗口
- GLUT只是呈现一个空白的白色屏幕
- 运行我的C++代码会给我一个空白控制台
- 我在我的程序中添加了一个void函数,它不接受任何参数,现在我的程序在运行时只返回一个空白终端
- ReadFile()返回一个空白数据
- 在c++中调试程序时,我得到一个空白屏幕
- 使用UDP和套接字进行客户端-服务器文本文件传输 在C++中,服务器创建一个空白文件
- 为什么我用WriteFile写入文件的每个字符之间都有一个空白
- 2D数组中的最后一个空白;矩阵
- 用c++排序,得到一个空白输出