如何访问字符串的元素?
How do I access the elements of a string?
我在访问二进制字符串的各个字符以查明它们是否已设置时遇到问题,我做错了什么?还是有更简单的方法?这是我的代码:
#include <iostream>
#include <string>
using namespace std;
float BinToDec(const string & bin) {
short length = bin.length();
float result = 1.0f;
const char * str = bin.c_str();
for (int i = 0; i < length; ++i) {
if ( &str[i] == "1") cout << "SET" << endl << endl;
else cout << "NOT SET" << endl << endl;
}
return result;
}
int main() {
string bin = "";
cout << "Input a binary number: ";
cin >> bin;
cout << BinToDec(bin) << endl << endl;
}
你可以直接迭代你的字符串bin
,不需要获取const char *
,这里也不需要&
运算符,因为通过使用[]
你已经取消引用并得到一个char
(这就是为什么你不应该将其与不是字符而是string literal
的"1"进行比较)
总而言之,我认为这将是一个更好的方法:
for (int i = 0; i < length; ++i) {
if ( bin[i] == '1')
cout << "SET" << endl << endl;
else
cout << "NOT SET" << endl << endl;
}
此外,将长度存储在short
中现在可能有效,但存在长度超过最大值的字符串short
,因此您应该使用size_t
.
它不适合您,因为:
- 您正在尝试获取一个子字符串以与字符串
"1"
进行比较,但是您的子字符串将在输入结束时终止...即可能远远超过1
字符。 - 将 C 字符串与
==
进行比较只是比较指针值
相反,只比较单个字符:
if ( str[i] == '1') cout << "SET" << endl << endl;
// ^ ^ ^
// | character literals are delimited by _single_ quotes
// no `&` required
但我完全不明白你为什么要使用.c_str()
;直接在bin
上操作,而不是创建这个 C 字符串str
:
float BinToDec(const string& bin)
{
size_t length = bin.length();
float result = 1.0f;
for (int i = 0; i < length; ++i) {
if (bin[i] == '1')
cout << "SET" << endl << endl;
else
cout << "NOT SET" << endl << endl;
}
return result;
}
我还更正了length
的类型。
如果您确定要使用 C 样式字符串执行此操作,请更改:
if ( &str[i] == "1") cout << "SET" << endl << endl;
自
if ( str[i] == '1') cout << "SET" << endl << endl;
这样,您就可以将str
的单个字符与'1'
、文字字符(而不是"1"
包含 1 个字符的字符串)进行比较。
您现有的代码将偏移量 i 的地址放入 c_str(),这实际上与从字符 i 开始的字符串的末尾相同,并将其与文本字符串"1"进行比较。 请注意,您不能像这样进行 C 样式的字符串比较,因为它会比较底层指针。
由于您正在尝试检查每个字符的值,因此请使用单引号而不是双引号。
float BinToDec(const string & bin) {
short length = bin.length();
float result = 1.0f;
const char * str = bin.c_str();
char c;
for (int i = 0; i < length; ++i) {
c = str[i];
// Use single quotes and not double quotes here
if ( c == '1') cout << "SET" << endl << endl;
else cout << "NOT SET" << endl << endl;
}
return result;
}
也就是说,我认为lccarrasco的方式是实现你想要实现的目标的正确方式。
相关文章:
- 将指针作为缓冲区传递到第一个字符串元素
- C++字符串问题-如何访问字符串元素
- 反转由空格分隔的字符串元素将返回比原始字符串更大的字符串
- 将向量元素与字符串元素进行比较,而不初始化向量
- 如何获取数组中字符串元素的字符数?[C++]
- 如何删除在没有STL的队列中存储在数组中的第一个字符串元素
- 比较两个向量的<Structs>字符串元素
- 将字符串元素转换为整数 (C++11)
- 如何使操作员返回引用字符串元素
- 访问字符串元素地址
- 第一个字符串元素的地址产生意外结果
- 在C 中的字符串向量的字符串元素中循环遍历所有字符
- 将字符串元素分配给结构数组中的结构
- C++检查字符串元素的相等性
- 将字符串元素转换为整数C++
- 试图将字符串元素与循环和索引进行比较,但索引不会增加
- C++ - 链表插入排序(字符串元素)
- C++将二维C字符串元素传递到函数中
- 从字符串元素中获取字符串
- 比较列表<string>和向量<string>中的字符串元素