一个简单的类,用于获取和打印字符串
A simple class for getting and printing a string
我刚刚开始使用类,在这段代码中,我试图有一个类,从用户获得一个字符串,计算它的长度,然后打印它。但是我得到了一些错误,我不明白它们是用来干什么的。我很感激你的帮助。
#include<iostream>
using namespace std;
class String
{
public:
String(); // constructor
void Print(); // printing the string
void Get(); // getting the string from the user.
int CountLng( char *); // counting length
~String(); // destructor
private:
char *str;
int lng;
} str1;
String::String()
{
lng=0;
str=NULL;
}
int CountLng( char *str)
{
char * temp;
temp=str;
int size=0;
while( temp !=NULL)
{
size++;
temp++;
}
return size;
};
void String::Get()
{
str= new char [50];
cout<<"Enter a string: "<<endl;
cin>>str;
};
void String::Print()
{
cout<<"Your string is : "<<str<<endl<<endl;
lng= CountLng( str);
cout<<"The length of your string is : "<<lng<<endl<<endl;
};
int main()
{
str1.Get();
str1.Print();
system("pause");
return 0;
}
在CountLng()
方法中,要检查字符串的结束,您需要检查指针指向的位置的内容,而不是指针位置本身:
while( *temp !=' ')//*temp gives you the value but temp gives you the memory location
{
size++;
temp++;
}
检查字符串结尾的标准是查找字符' '
或NUL
。指向字符串末尾的指针不一定是NULL。
此外,在Get()
方法中,字符串大小被限制为50个字符。当将两个String对象一起添加时,这将是一个问题。您需要使用std::copy和重新分配您的字符数组,使字符串大小动态,并使您的字符串大小在溢出的情况下更大
-
int CountLng(char *str)
应该是int String::CountLng(char *str)
,因为它是String
类的方法 -
同样,你在类声明中定义了析构函数,但没有定义析构函数体:
String::~String()
{
}
以上代码有多个问题
- 你正在使用str1 a应该是字符串对象,但没有声明它。
- 成员函数用::语法声明
- Destructor没有body
我已经调整了你的程序,以摆脱这些问题,比较它与你的原始程序,看看差异
#include<iostream>
using namespace std;
class String
{
public:
String(); // constructor
void Print(); // printing the string
void Get(); // getting the string from the user.
int CountLng( char *); // counting length
~String(){ if (str) delete []str; }; // destructor
private:
char *str;
int lng;
};
String::String()
{
lng=0;
str=NULL;
}
int String::CountLng( char *str)
{
char * temp;
temp=str;
int size=0;
while( *temp !=' ')
{
size++;
temp++;
}
return size;
};
void String::Get()
{
str= new char [50];
cout<<"Enter a string: "<<endl;
cin>>str;
};
void String::Print()
{
cout<<"Your string is : "<<str<<endl<<endl;
lng= CountLng( str);
cout<<"The length of your string is : "<<lng<<endl<<endl;
};
int main()
{
String str1;
str1.Get();
str1.Print();
system("pause");
return 0;
}
相关文章:
- 如何巧妙地编写两个函数——一个用于检查是否存在解决方案,另一个用于获取所有解决方案
- 用于获取枚举值的用户输入
- 谁能告诉我,程序中的错误是什么?该程序仅用于获取文件扩展名
- 为什么用于获取有关名称的输入的语法不起作用?
- 用于获取数组长度的指针数学
- 当 getline 用于获取整个字符串时,程序崩溃
- “noexcept”说明符用于获取者和二传手
- 模板结构的多个声明,用于获取枚举,描述模板类型
- 用于获取以元音和辅音开头的单词数量的程序返回错误的答案
- 用于获取多个容器参考的variadic模板
- 可以用于获取参数类型的 decltype
- 用于获取函数签名的 C++ 正则表达式
- 一个模板函数,用于获取向量中的最大值及其相应的索引
- 用于获取 C++ 中 POSIX 时区的 API
- 用于获取JPEG图像大小的C++库
- 一个简单的类,用于获取和打印字符串
- 用于获取HTML表内容的正则表达式
- 用于获取窗口控件的 API 方法
- 用于获取active directory票证的Win32 API
- 用于获取nothrow运算符new地址的C++语法