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

strlen function incompatible w/loop, loop variable incompatible

本文关键字:不兼容 循环 变量 函数 strlen      更新时间:2023-10-16

好吧,我到处都找不到合适的方法。我只想接收一个字符串,将该字符串放入数组中并输出内容。然而,我想根据用户输入的字符串的大小来做这件事。我遇到了一些奇怪的错误,比如不兼容,我想知道为什么,谢谢。

#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;
   }
相关文章: