索引字符数组 - 指针问题

时间:2013-03-19 10:32:25

标签: c++ arrays pointers indexing char

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

嗨! 我在这里尝试两件我无法做的事情。我正在尝试在main中创建一个未指定长度的char数组,并且我正在尝试计算函数countCharacters中char数组中的单词数。但是密码[index]不起作用。

编辑:我正在做家庭作业,所以我只能使用cstrings。 编辑2:我也不允许使用“strlen”函数。

1 个答案:

答案 0 :(得分:1)

首先更换

char password[];

通过

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

然后替换:

cin >> *password;

通过

cin >> password;

而不是"\0"你应该放'\0'

P.S。在C ++中没有未指定长度的char数组,你应该使用std :: string代替(http://www.cplusplus.com/reference/string/string/):

#include <string>

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