<分区>
为了介绍 CS 分配,我在 Visual Studio 2010 中编写了一个 C++ 程序,它返回一个整数并接受一个指向 C 字符串的指针作为参数。我知道除了 int main 之外我还需要创建一个函数才能成功,但我不确定如何初始化指向预定义 char 数组的 char 指针数组(如果可能)。
该程序的目的是在预定义的限制范围内从用户那里获取评论,然后告知该用户该评论有多少个字符(包括空格)。
错误是:“char”类型的值不能赋值给“char *”类型的实体;
这是我无法编译的程序:
#include "stdafx.h"
#include <iostream>
#include <string>
#include <conio.h>
using namespace std;
//function protoype
void evalStr(char arr[]);
//variable
int length;
//main function
int main()
{
const int SIZE = 201;
char arr[SIZE];
char *str[SIZE];
cout << "Please enter a comment under " << (SIZE - 1) << " characters to calculate it's length: ";
*str = arr[SIZE];
cin.getline(arr, SIZE);
length = strlen(*str);
evalStr(arr);
system("PAUSE");
return 0;
}
//function defintion
/* get the string
count the number of characters in the string
return that number
*/
void evalStr(char arr[])
{
printf("The length of the entered comment is %d characters\n", length);
}
如果有使用 char 指针数组或指向字符串的指针的通用方法,则可以重做此代码以返回字符串的值,而不是使用 printf 语句。我做错了什么?
编辑:这是该程序的更新版本,它可以编译、运行并在达到或超过字符限制时通知用户。
// Accept a pointer to a C-string as an argument
// Utilize the length of C-string in a function.
// Return the value of the length
// Display that value in a cout statement.
#include "stdafx.h"
#include <iostream>
#include <string>
#include <conio.h>
using namespace std;
//variables
const int SIZE = 201;
int length;
char arr[SIZE];
char *str;
//main function
int main()
{
str = &arr[0];
// Size - 1 to leave room for the NULL character
cout << "Please enter a comment under " << (SIZE - 1) << " characters to calculate it's length: ";
cin.getline(arr, SIZE);
length = strlen(str);
if (length == (SIZE - 1))
{
cout << "Your statement has reached or exceeded the maximum value of "
<< length << " characters long.\n";
}
else
{
cout << "Your statement is ";
cout << length << " characters long.\n";
}
system("PAUSE");
return 0;
}
//function defintion
/* get the string
count the number of characters in the string
return that number
*/
int countChars(int)
{
length = strlen(str);
return length;
}