使用指针处理字符串
Working with strings using pointers
大家好,这是我的代码:
#include <iostream>
#include <string>
using namespace std;
void writeDown(string*t)
{
for (int i = 0; *(t+i)!=NULL; i++)
{
cout << *(t+i) <<endl;
}
}
int main()
{
string t;
getline(cin, t);
string *wsk = &t;
writeDown(wsk);
return 0;
}
所以我只需插入一个字符串,程序应该在新行中为其中的每个字符cout<<
。但这里是弹出的:
binary '!=' : no operator found which takes a left-hand operand of type 'std::string' (or there is no acceptable conversion)
我做错了什么?
Btw。我在VS 2013中为Win Desktop工作(顺便说一句,第2卷-这是C++编码的好环境吗?-2015年,但它在我的笔记本电脑上运行缓慢)
代码在很多级别上都很糟糕,但为了保持简单并回答您的问题,我可能会使用迭代器。如果你使用的是C++,那就忘了旧的C风格吧。
试试这个:
void writeDown(const string & t)
{
for (string::const_iterator it = t.begin();
it != t.end();
++it)
{
cout << *it << endl;
}
}
请注意,writeDown
不再将指针作为参数,而是要打印的字符串的常量引用。
您必须更改主菜单才能调用writeDown
:
string t;
getline(cin, t);
writeDown(t);
如果你坚持使用"数组"方法,你就必须这样使用它,但是。。。
void writeDown(const string & t)
{
for (int i = 0; t.c_str()[i] != NULL; i++)
{
cout << t.c_str()[i] << endl;
}
}
相关文章:
- 在for循环中使用auto vs decltype(vec.size())来处理字符串的向量
- 对字符串进行排序时,在c++中处理sort()
- 是否可以在c++中处理字符串流中的各个元素
- 方便地对C++中的所有字符串文字进行模糊处理
- 在处理任何字符大小的模板中使用字符串文本
- 我如何处理有关输入的字符串大小超过字符数组设置大小的错误?
- 如何以这种方式处理字符串数组
- 在C++中使用指针进行字符串处理
- 如何在我的C++程序中调试字符串处理
- 选择编码和字符串处理
- C++中的Unicode字符串处理
- C字符串处理函数获取子字符串
- C++ Win32:基本字符串处理
- 为什么 Ruby 字符串处理速度很慢
- 将 java 字符串处理成原生 C/C++ for Android Studio+NDK
- c++中的字符串处理和内存管理
- c和c++混合编程中的字符串处理
- C++ 标准输入的 IO 优化和字符串处理
- c++字符串处理中的重复字符跳过
- 动态数组 - C++ - 重载运算符>>并使用 C 样式字符串处理输入