user1784297
user1784297

Reputation: 105

Indexing an array of chars - issue with pointers

#include <iostream>
#include <cstring>
using namespace std;

void getInput(char *password, int length)
{
    cout << "Enter password: ";
    cin >> *password;
}
int countCharacters(char* password)
{
    int index = 0;
    while (password[index] != "\0")
    {
        index++;
    }
    return index;
}
int main()
{
    char password[];
    getInput(password,7);
    cout << password;
    return 0;
}

Hi! I'm trying two things here which I'm unable to do atm. I'm trying to create a char array with unspecified length in main, and I'm trying to count the number of words in the char array in the function countCharacters. But password[index] doesnt work.

EDIT: I'm doing a homework assignment, so I have to use cstrings only. EDIT2: And I'm not allowed to use the "strlen"-function either.

Upvotes: 0

Views: 198

Answers (1)

artahian
artahian

Reputation: 2093

At first replace

char password[];

by

char password[1000]; // Replace 1000 by any maximum limit you want

And then replace:

cin >> *password;

by

cin >> password;

Also instead of "\0" you should put '\0'

P.S. There is no char array with unspecified length in C++, you should use std::string instead(http://www.cplusplus.com/reference/string/string/):

#include <string>

int main() {
    std::string password;
    cin >> password;
    cout << password;
    return 0;
}

Upvotes: 1

Related Questions