求救高手,一个编程题!

来源:百度知道 编辑:UC知道 时间:2024/09/22 01:36:02
题目的要求是这样的。。编一个程序从 string对象中去掉标点符号。要求输入到程序的字符串必须含有标点符号,输出结果则是去掉标点符号后的string对象。 下面是我写的代码,运行之后出现一些奇怪的字符,想了半天也没想明白,虽然算法比较笨了点,但应该不会出错。希望高手指点。

#include<iostream>
#include<string>

using std::cout;
using std::cin;
using std::endl;
using std::string;

int main()
{
//待测字符串的输入
cout<<"请输入带有标点符号的字符串:"<<endl;
string str;//待测字符串
cin>>str;

const string::size_type size_of_str=str.size();//定义并确定待测字符串的大小

string::size_type size_of_str_punct=0;//定义待测字符串中标点符号的个数
//确定待测字符串当中含有标点的个数
for(string::size_type i=0;i<size_of_str;i++)
{
if(ispunct(str[i]))
{
size_of_str_punct++;
}
}

int sos=size_of_str;
int sosp=size_of_str_punct;
char *temp=new char[sos-sosp+1];
int k=0;
//给temp进行赋没有标点符号的赋值
for(string::size_type j=0;j<size_of_str;j++)
{
if(!ispun

是输出一些乱码了吗?看如下程序段

31 int k=0;
32 //给temp进行赋没有标点符号的赋值
33 for(string::size_type j=0;j<size_of_str;j++)
34 {
35 if(!ispunct(str[j]))
36 {
37 temp[k]=str[j];
38 k++;
39 }
40 }
41 temp[k]='\0';
42
我想是由于你没在后面加一个字符串结束标志而造成的,在循环的后面加句temp[k]='\0';即可