我100%確定我的代碼錯誤地確定了數組的大小 當我將hello作爲輸入並設置strArray [5]時,它可以正常工作。但問題是我不知道輸入的大小有多大,所以我只是放80(因爲這是最大的可能)遇到陣列問題
這是我的代碼。
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;
main()
{
string str1;
char strArray[80];
cout << "Enter string: ";
getline(cin, str1);
transform(str1.begin(), str1.end(), str1.begin(), ::tolower);
str1.erase(remove(str1.begin(),str1.end(),' '),str1.end());
for(int i = 0;i < str1.length(); i++)
{
if(str1[i] == ',' || str1[i] == '.')
{
str1.erase(i,1);
}
}
for(int i=0;i<str1.length();i++)
{
strArray[i] = str1[i];
}
char tempChar;
for(int i = 0; i < (sizeof(strArray)/sizeof(*strArray))-1; i++)
{
for(int j = 0; j < (sizeof(strArray)/sizeof(*strArray)-1); j++)
{
if(strArray[j+1] < strArray[j])
{
tempChar = strArray[j];
strArray[j] = strArray[j+1];
strArray[j+1] = tempChar;
}
}
}
cout << strArray << endl;
return 0;
}
只是使用字符串,而不是char表 – Ardel
你想在該循環中做什麼? – Brian
你只是想在刪除逗號和句點後找到字符串的長度嗎? – Matthew