【发布时间】:2020-06-26 22:04:26
【问题描述】:
我已经编写了一个程序,它打算接受一个输入并按字符的升序返回输出。
例子:
场景 1:给定输入“Hello Rohit”,该方法应返回“ehHillooRt”
场景 2:给定输入“Hello Rohit!”,该方法应返回错误消息(“Invalid character ! at position 12”),指定第一次出现和无效字符的位置。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <bits/stdc++.h>
using namespace std;
int main()
{
string str;
int i, count, n;
cout << "Enter a sentence : ";
getline(cin, str);
for (i = 0; str[i] != '\0'; i++) {
if (str[i] == ' ')
count++;
}
string strWords[count + 1];
short counter = 0;
for (short i = 0; i < str.length(); i++) {
if (str[i] == ' ') {
counter++;
i++;
}
strWords[counter] += str[i];
}
for (i = 0; i < strWords[i].length(); i++) {
string temp = strWords[i];
sort(temp.begin(), temp.end());
cout << temp << " ";
}
return 0;
}
【问题讨论】:
-
请修正你的缩进(做缩进)和垂直间距(你不需要所有的垂直空间)。这将使代码更易于阅读。
-
与您的问题无关,但请花点时间阅读Why should I not #include <bits/stdc++.h>?
-
还要注意 C++ 没有variable-length arrays。使用例如
std::vector代替。 -
问题陈述不要求将输入拆分为单词。
"Hello Rohit" -> "ehHillooRt"的示例显然忽略了单词边界(注意两个os 如何在输出中一起出现)。大约五分之四的代码专门用于拆分成单词。 -
请花点时间刷新How to Ask,以及this question checklist。您显示的代码有什么问题?对于您作为示例提供的输入,actual 输出是什么?当你构建或运行你的程序时会发生什么?您是否尝试过在调试器中逐句逐句执行代码?