Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/133.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 计算字符串中的单个字长_C++_String - Fatal编程技术网

C++ 计算字符串中的单个字长

C++ 计算字符串中的单个字长,c++,string,C++,String,是的,我不知道为什么输出中会出现黑色三角形,但这是精确的输出。不考虑终止的空字符,因此第二个if条件在遇到字符串结尾时返回false 在我看来,for语句中的语句可以简化为 Four 4 score 5 and 3 seven 5 years 5 ▼ 2 6 您尝试检查的字符串比预期长一个字符: char a[] = "Four score and seven years ago"; std::istringstream ss(a); std::string s; while(ss &

是的,我不知道为什么输出中会出现黑色三角形,但这是精确的输出。

不考虑终止的空字符,因此第二个
if
条件在遇到字符串结尾时返回
false

在我看来,
for
语句中的语句可以简化为

Four 4
score 5
and 3
seven 5
years 5
▼  2
6

您尝试检查的字符串比预期长一个字符:

char a[] =  "Four score and seven years ago";

std::istringstream ss(a);
std::string s;

while(ss >> s) {
    std::cout << s << ' ' << s.length() << '\n';
}
此大小包括终止的空字符。如果我要处理赋值,我要么在
char const*
上使用运算符,并使用检查终止空字符的C约定,要么将数组转换为
std::string
并处理迭代器,然后检查结束迭代器。我还认为,你必须对照一个单词的结尾检查的逻辑假设单词之间正好有一个空格

您的
countwords()
函数似乎处理C约定。在使用
之前,您的
main()
函数应该检查
a[i]
是否为空!isspace(static_cast(a[0])
:由于
isspace(0)
isalnum(0)
false,所以
countwords()起作用。然而,仅仅因为
0
不是空格,就意味着它是单词的一部分。还应该考虑终止空字符一个字分隔符,即报告一个词的长度的条件应该是

int size = sizeof(a)/sizeof(char);
if(!a[i]| | isspace(static_cast(a[i]))
std::字符串字;
std::istringstream str(a);
while(str>>word){
总和+=长度();

std::cout尽管在您的代码中它是正常的(因为您所有的
char
s都在ASCII范围内),但请注意,将
char
立即传递到
isdigit()
(或任何其他字符分类函数)可能会导致未定义的行为:参数必须是正的
int
,并且
char
可能是有符号的(在大多数平台上,它是有符号的)。如果传递负值,例如,在处理我的第二个名字时,您会得到未定义的行为。因此,您应该始终将
char
转换为
无符号char
,例如:
isdigit(static_cast(a[i]))
char a[] =  "Four score and seven years ago";

std::istringstream ss(a);
std::string s;

while(ss >> s) {
    std::cout << s << ' ' << s.length() << '\n';
}
int size = sizeof(a)/sizeof(char);
if(!a[i] || isspace(static_cast<unsigned char>(a[i])))
std::string word;
std::istringstream str(a);
while (str >> word) {
    sum += str.length();
    std::cout << word << ' ' << word.length << '\n';
}