strlen function incompatible w/loop, loop variable incompatible

172 views Asked by At

Ok I've been looking everywhere and I can't find the proper way to do this. I simply want to take in a string, put that string in the array and output the contents. However, I want to do it dependent on the size of the string which the user enters in. And I was getting weird errors such as incompatibility and I would like to know why please, thank you.

#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;
}
3

There are 3 answers

1
user3050633 On

i hope it will work..

#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;
   }
0
juanchopanza On

std::array needs a compile-time size, so cannot be instantiated with strlen. Furthermore, strlen does not work with std::string, it expects a pointer to char, pointing to the beginning of null terminated string.

You could use an std::vector<char> instead:

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] << ' ';

On the other hand, why not just use the string y directly? Do you really need the "array"?

for(int i = 0; i < y.size(); ++i)
    std::cout << y[i] << ' ';
3
egur On

std::array is a wrapper template class around a C static array. This means that it's dimensions must be known at build time (not runtime).

Here's a short version of a working code that's also a little faster since string::length() is called once.

#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;
}

If you like pointer tricks and take advantage that string's buffer is contiguous in memory (by the C++ standard) your code can look like:

int main()
{
    string y;

    cout << "Enter value";
    getline(cin, y );

    for( const char* p = &y[0]; *p; ++p )
        cout << *p << ' ';

    system( "PAUSE" );
    return 0;
}