确定传递值的数组的大小
Determining the size of a array which was passed a value
#include <iostream>
using namespace std;
int main(){
char word[100];
char count;
int j=0;
cout<<"Enter a word or a phrase"<<endl;
cin>>word;
cout<<endl<<word<<endl;
j=sizeof(word);
cout<<j;
}
我在上面的程序中想做的是找出用户输入的字符串(单词)的长度,但是上面的程序只给出了整个数组的大小,即100。
数组的大小确实是 100。
但是您正在查找该数组中设置的字符数,直到第一个空字节,即数组中“C 字符串”的长度。
strlen
这样做。
不过,如果没有其他原因,只是你目前没有执行边界检查,那么如果你的用户输入了 100 个或更多字符的文本,你会更好 std::string
溢出你的数组。这充其量是一个讨厌的错误,最坏的情况是常见的安全风险。
char word[100];
这是一个 C 风格的字符串。它们以 null 结尾——这意味着它们以 [=12=]
结尾。示例:
INPUT: Hello!
word: 'H', 'e', 'l', 'l', 'o', '!', '[=11=]' // <-- NULL-TERMINATOR
在 C++ 中不推荐使用这些类型的字符串,通常只能在遗留代码中找到。请改用 std::string
(#include <string>
) 及其 length
函数!
#include <iostream>
#include <string.h>
using namespace std;
int main(){
char word[100];
cout << "Enter a word or a phrase" << endl;
cin >> word;
cout<< strlen(word) <<endl;
}
编辑: 这是正确的,您需要包括 并使用 strlen 它将根据 '/0' 符号找到长度这意味着 c_str.
结束
#include <iostream>
using namespace std;
int main(){
char word[100];
char count;
int j=0;
cout<<"Enter a word or a phrase"<<endl;
cin>>word;
cout<<endl<<word<<endl;
j=sizeof(word);
cout<<j;
}
我在上面的程序中想做的是找出用户输入的字符串(单词)的长度,但是上面的程序只给出了整个数组的大小,即100。
数组的大小确实是 100。
但是您正在查找该数组中设置的字符数,直到第一个空字节,即数组中“C 字符串”的长度。
strlen
这样做。
不过,如果没有其他原因,只是你目前没有执行边界检查,那么如果你的用户输入了 100 个或更多字符的文本,你会更好 std::string
溢出你的数组。这充其量是一个讨厌的错误,最坏的情况是常见的安全风险。
char word[100];
这是一个 C 风格的字符串。它们以 null 结尾——这意味着它们以 [=12=]
结尾。示例:
INPUT: Hello!
word: 'H', 'e', 'l', 'l', 'o', '!', '[=11=]' // <-- NULL-TERMINATOR
在 C++ 中不推荐使用这些类型的字符串,通常只能在遗留代码中找到。请改用 std::string
(#include <string>
) 及其 length
函数!
#include <iostream>
#include <string.h>
using namespace std;
int main(){
char word[100];
cout << "Enter a word or a phrase" << endl;
cin >> word;
cout<< strlen(word) <<endl;
}
编辑: 这是正确的,您需要包括