[英]How to get the size of the used space in an array? (NOT sizeof); c++
#include<iostream>
using namespace std;
int main()
{
char arr[200];
while(1) {
cin >> arr;
int i = sizeof(arr);
cout << "The arr input is "<< arr
<< " and the size of the array is "<< i << endl;
}
return 0;
}
對於34的輸入,此代碼輸出:arr輸入為34,數組的大小為200
而我希望它獲得數組已使用空間的大小。 所以對於最后一個輸入我想要它輸出:arr輸入為34並且數組的大小為2
有人可以告訴我如何嗎?
也許您想在這里strlen(arr)
。 它必須以null終止,否則cout << arr
將不起作用。
您將需要#include <cstring>
在一般情況下,沒有自動的方法可以做您想要的事情-您需要以某種方式保持跟蹤,要么使用自己的計數器,要么通過為數組添加一個“無效”值(您定義的)(您定義)並搜索以查找使用的元素的末尾(這就是C樣式字符串中的'\\ 0'終止符)。
在您發布的示例代碼中,數組應接收以N結尾的C樣式字符串,您可以使用該知識來計算有效元素的數量。
如果您使用的是C ++或其他具有更高級數據結構的庫,則可以使用一個可以為您跟蹤此類事情的庫(例如std::vector<>
)。
數組已用空間的大小
哪有這回事。 如果您有200個字符的數組,那么您有200個字符。 數組沒有“已用”和“未用”空間的概念。 它僅適用於C字符串,因為約定以0字符終止。 但是話又說回來,數組本身不知道它是否持有C字符串。
以一種較少參與的方式,您可以對每個字符進行計數,直到僅用while循環擊中空值。 它將做與strlen()完全相同的事情。 另外,在實踐中,您應該使用cin進行類型檢查,但是我認為這只是一個測試。
#include <iostream>
using namespace std;
int main()
{
char arr[200];
int i;
while(1) {
cin >> arr;
i=0;
while (arr[i] != '\0' && i<sizeof(arr))
i++;
cout << "The arr input is "<< arr
<< " and the size of the array is "<< i << endl;
}
return 0;
}
只是為了完整性,這是一個更像C ++的解決方案,它使用std::string
而不是原始char
數組。
#include <iostream>
#include <string>
int
main()
{
while (std::cin.good()) {
std::string s;
if (std::cin >> s) {
std::cout
<< "The input is " << s
<< " and the size is " << s.length()
<< std::endl;
}
}
return 0;
}
它不使用數組,但是它是解決此類問題的首選方法。 通常,您應該嘗試適當地用std::string
和std::vector
替換原始數組,用shared_ptr
( scoped_ptr
或shared_array
,最合適)替換原始指針,並用std::stringstream
替換snprintf
。 這是簡單編寫更好的C ++的第一步。 將來您會感謝您的。 我希望我幾年前遵循了這個建議。
試試吧
template < typename T, unsigned N >
unsigned sizeOfArray( T const (&array)[ N ] )
{
return N;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.