Search code examples
c++stringstrlen

strlen defaulting to '40'?


new programmer here starting with the basics. I need to write a code that checks for the length of a string (line) and does things with it. I'm working on getting the length correct before I start with the next part of the task.

What's happening when I run the below code is strlen(string1) seems to be defaulting to '40' no matter what I enter?

I'm not sure what's going wrong! Any help would be greatly appreciated.

#include <iostream>
#include <string.h>
#include <string>
using namespace std;

char line, just, jline;
void prompt();

int main() {
  cout << "Enter a line of text: " << endl;
  char string1[line];
  cin >> line;

  char string2[] = "1234567890123456789012345678901234567890";

  line = strlen(string1);
  just = strlen(string2);

  cout << "Length of string is: " << strlen(string1) << endl;

  if ((strlen(string1)) > (strlen(string2))) {
    cout << "Error, your line must be less than 40 characters" << endl;
  }
}

Solution

  • There are 2 problems with your code as described below:

    Problem 1

    In standard C++ the size of an array must be a compile time constant. This means that the following is incorrect in your program:

    char string1[line]; //not standard C++ because line is not a constant expression
    

    Problem 2

    Note that there is another problem with this. Since line is a global variable it will be statically initialized to 0. Thus char string1[line]; is actually equivalent to char string1[0];.

    `But from array declarators documentation:

    If the expression is a constant expression, it shall have a value greater than zero.

    Thus, char string1[line]; is invalid for this reason also.

    Solution

    Better would be to std::string and as shown below:

    #include <iostream>
    #include <string>
    
    int main() {
        std::cout << "Enter a line of text: " << std::endl;
        std::string inputLine;
        std::getline(std::cin, inputLine);//take input from user and put it into inputLine
        
        std::string var = "1234567890123456789012345678901234567890";
        
    //----------------------------------------------------vvvvv----------->use size member function of std::string
        std::cout << "Length of string is: " << inputLine.size() << std::endl;
        
        if (inputLine.size() > var.size()) {
            std::cout << "Error, your line must be less than 40 characters" << std::endl;
        }
        else 
        {
            std::cout<<"valid input"<<std::endl;
        }
    }
    

    Demo.

    In the above snippet, we have used std::string::size to know the size/length of the std::string.


    Also, the use of global variables should be avoided wherever possible. Refer to Are global variables bad?.