2013-03-19 46 views
0
#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; 
} 

嗨! 我在这里尝试两件事情,我无法做atm。我试图在main中创建一个未指定长度的char数组,并且我试图计算countCharacters函数中char数组中单词的数量。但密码[索引]不起作用。索引一个字符数组 - 指针问题

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

+0

有根本没有这样的事情未指定长度的数组。可以使用动态分配的内存,但是你应该使用'std :: string'来封装它。 – 2013-03-19 10:37:19

+0

getInput函数的'length'参数是什么?它不在那里使用。 – ArtemStorozhuk 2013-03-19 10:43:32

+0

密码长度为7.它是密码长度的限制。在我的任务中,我将get长度作为getInput中的参数,并将输入限制为6个符号+“\ 0”。但是如何? – user1784297 2013-03-19 10:47:33

回答

1

起初更换

char password[]; 

通过

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

,然后替换:

cin >> *password; 

通过

cin >> password; 

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

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

#include <string> 

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

我正在做家庭作业,所以我只能使用cstrings。 – user1784297 2013-03-19 10:42:08