我從用戶那里獲取字符陣列并試圖找到它的大小,但它以某種方式不起作用。
我的代碼如下所示:
int main()
{
char str[] ={}
cout << "Enter a characters ";
cin >> str;
int arrSize = sizeof(str);
cout << arrSize;
return 0;
}
當我像下面的代碼一樣定義陣列時,它將起作用:
int main()
{
char str[] ={"1234"}
int arrSize = sizeof(str);
cout << arrSize;
return 0;
}
我不習慣 C ,請有人幫助我。
uj5u.com熱心網友回復:
歡迎來到 C stdlib 的奇妙世界。如果使用 c 更好地使用 stdlib 的全部力量。
string str;
std::getline(cin, str);
那么你可以使用 str.size() 來獲取它的長度。查找 cppreference.com 以獲取有關 stdlib 函式和類的任何幫助。
uj5u.com熱心網友回復:
C 中的陣列是靜態的。創建空字符陣列后,char str[] = {}您不能用任意數量的字符填充它。靜態 C 風格陣列的大小在編譯時計算,以及sizeof()運算子。如果由于某種原因確實必須使用 C 樣式字串(字符陣列),請首先在陣列中分配足夠的空間,然后使用strlen()函式來確定字串長度。
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char str[256];
cin >> str;
int arrSize = strlen(str);
cout << arrSize;
}
但是,由于您使用的是 C (而不是 C),因此最好std::string在您的情況下使用。
#include <iostream>
using namespace std;
int main()
{
string str;
cin >> str;
int arrSize = str.size();
cout << arrSize;
}
順便說一句,你不需要return 0;在 C 中。
uj5u.com熱心網友回復:
您給定的代碼片段中有兩個錯誤:
錯誤一
在 C 中,陣列的大小必須是編譯時常量。所以你不能寫這樣的代碼:
int n = 10;
int arr[n]; //incorrect
正確的寫法是:
const int n = 10;
int arr[n]; //correct
出于同樣的原因,以下代碼在您的代碼中也不正確:
char str[] ={};//this defines(and declares) an empty array. This statement is not fine(that is it is incorrect) because we cannot have 0 size arrays in c
cin >> str; //incorrect because a built in array is fixed size container and you cannot add more elements(than its size) to it(both by user input or by the programmer itself)
錯誤 1 ??的解決方案
char str[100] ={}; //this defines an array of fixed size 100.
cin >> str; //this is correct now, but note that you can only safely enter upto 100 characters. If you try to add more than 100 than this will also become incorrect
錯誤 2
您以錯誤的方式計算陣列的大小。正確的方法是:
int arrSize = sizeof(str)/sizeof(char);// since sizeof(char) = 1 you can omit the denominator but note you can omit it only for char type
使用正確的式sizeof(str)/sizeof(char)的其他型別的喜歡為陣列重要double,int等等,這是通式。但sizeof(char) = 1;既然如此,您使用的公式是正確的(僅適用于char)。所以如果你有一個陣列,double那么你應該使用sizeof(str)/sizeof(double);.
另外,請注意,您可以/應該改為使用std::string從用戶那里獲取輸入,然后使用size()方法來計算輸入的時間長度:
std::string str;
std::cin >> str;
std::cout<<"size is "<<str.size()<<std::endl;
請注意,您還可以std::size在 C 17 中使用來查找陣列的大小。(@eerorika 在下面的評論中指出)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/339980.html
