c++ - strlen 函数与循环不兼容,循环变量不兼容

标签 c++ loops incompatibility

好吧,我到处都在寻找,但找不到正确的方法来做到这一点。我只是想接收一个字符串,将该字符串放入数组中并输出内容。但是,我想根据用户输入的字符串的大小来执行此操作。我遇到了奇怪的错误,例如不兼容,我想知道为什么,谢谢。

#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 的指针, 指向空终止字符串的开头。

你可以使用 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] << ' ';

关于c++ - strlen 函数与循环不兼容,循环变量不兼容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20344857/

相关文章:

c++ - `gcc -E -P -C` 添加额外注释

c++ - 归并排序计数错误 : Counting Inversions

java - 如何修复 java.lang.UnsupportedClassVersionError : Unsupported major. 次要版本

bash - 为什么我的循环有时不读取整行?

loops - 在 lisp 中求和斐波那契数

ios - 从“NSData *”分配给“NSMutableData *”的指针类型不兼容

Python 日志记录在 2.5 和 2.6 之间不兼容

C++ 使用迭代器访问 vector 的指针元素

C++继承无法识别

Python 2.6 聊天循环问题。不能同时接收和发送