strlen函数与循环不兼容,循环变量不兼容
strlen function incompatible w/loop, loop variable incompatible
好吧,我到处都找不到合适的方法。我只想接收一个字符串,将该字符串放入数组中并输出内容。然而,我想根据用户输入的字符串的大小来做这件事。我遇到了一些奇怪的错误,比如不兼容,我想知道为什么,谢谢。
#include <iostream>
#include <array>
#include <string>
using namespace std;
int main()
{
int x = 4000;
string y;
cout << "Enter value";
getline(cin, y);
array<char, strlen(y)>state;
for(int i=0; i<strlen(y); ++i)
cout << state[i] << ' ';
system("PAUSE");
return 0;
}
std::array
需要编译时大小,因此不能用strlen
实例化。此外,strlen
不与std::string
一起工作,它希望有一个指向char
的指针,指向以null结尾的字符串的开头。
你可以用std::vector<char>
代替:
std::string y;
std::cout << "Enter value";
std::getline(std::cin, y);
std::vector<char> state(y.begin(), y.end());
for(int i = 0; i < state.size(); ++i)
std::cout << state[i] << ' ';
另一方面,为什么不直接使用string
y
呢?你真的需要"数组"吗?
for(int i = 0; i < y.size(); ++i)
std::cout << y[i] << ' ';
std::array是一个围绕C静态数组的包装器模板类。这意味着它的维度必须在构建时(而不是运行时)已知。
下面是一个工作代码的简短版本,由于字符串::length()被调用一次,所以速度也快了一点。
#include <iostream>
#include <string>
using namespace std;
int main()
{
string y;
cout << "Enter value";
getline(cin, y );
for( size_t i = 0, yLen = y.length(); i < yLen; ++i )
cout << y[i] << ' ';
system( "PAUSE" );
return 0;
}
如果你喜欢指针技巧,并利用字符串的缓冲区在内存中是连续的(根据C++标准),你的代码可以看起来像:
int main()
{
string y;
cout << "Enter value";
getline(cin, y );
for( const char* p = &y[0]; *p; ++p )
cout << *p << ' ';
system( "PAUSE" );
return 0;
}
我希望它能起作用。。
#include "stdafx.h"
#include <iostream>
#include <array>
#include <string>
using namespace std;
int main()
{
int x = 4000;
string y;
cout << "Enter value";
getline(cin, y );
char *b = new char[y.length()];
int j=y.length();
//array< char, strlen(y)>state;
for( int i = 0; i<j; ++ i )
{//whatever uu want
}
//cout << state[i] << ' ' ;
system( "PAUSE" );
return 0;
}
相关文章:
- 当调用switch语句中的函数时(即使函数不包含循环),似乎是永不结束的循环的问题
- 我收到同义重复编译器错误。我应该如何修复"类型"X"的参数与类型"X"的参数不兼容?
- 字符类型转换不兼容
- Qt:如何使不兼容的发送方/接收方参数兼容?
- 视觉工作室 2017;启用 /permissive 时,类型 "const wchar_t *" 的参数与类型 "PWSTR" 的参数不兼容
- 使用不兼容的分配器复制分配无序列图
- 类型为 "int*" 的参数与 C++ 中错误类型"int**"参数不兼容
- 该对象具有与成员函数不兼容的类型限定符.为什么会出现此错误?
- 我正在尝试将表的地址传递给要在另一个函数中使用的指针,但得到不兼容的指针类型
- 为什么范围算法与 std 的迭代器不兼容?
- Winpcap Findalldevs const char * 与 char * 不兼容
- 0 的 2D 数组 不相关循环的破坏逻辑 - C++
- C++ 类型的参数与 void (__cdecl*)(void) 类型的参数不兼容,当调用 std::atexit()
- 修改向量中的字符串?(不使用循环)
- 将"std::string {aka std::basic_string}"赋值中的不兼容类型<char>
- 如何在C++中停止调用不兼容的方法?
- 特征获取索引数组,其中向量中的值为真(不需要循环)
- OPENCL 警告:不兼容的指针类型将'float __global[16]'传递给类型为 '__global float4 的参数 *
- strlen函数与循环不兼容,循环变量不兼容
- 在自包含向量循环中删除时"矢量迭代器不兼容"