###### Gargan

2016-04-10 13:39 阅读 1.2k

# 从字符串到分数的构造器，在构造器函数的定义处调试时有“写入位置访问冲突”问题

#define _CRT_SECURE_NO_WARNINGS
#include
#include
using namespace std;
class Fraction
{

private:
int num, den;
public:
Fraction(char s[10]);
void set(int n, int d){ num = n; den = d;normalize(); }
int get_x(){ return num; }
int get_y(){ return den; }
private:
void normalize();
int lcd(int a,int b);
};

int main()
{
Fraction p3("12,14");
cout << p3.get_x() << endl;
cout << p3.get_y() << endl;
system("pause");
return 0;
}
Fraction::Fraction(char s[])
{
int n = 0;
int d = 1;
char *p1,*p2;
p1 = strtok(s,"/,");
p2 = strtok(NULL,"/,");
if (p1 != NULL)
{
n = atoi(p1);
}
if (p2 != NULL)
{
d = atoi(p2);
}
set(n, d);
}
void Fraction::normalize()
{
if (num == 0 || den == 0)
{

num = 0;
den = 1;
}
int n = lcd(num,den);
num /= n;
den /= n;
}
int Fraction::lcd(int a,int b)
{
if (b == 0)
{

return a;
}
else return lcd(b,a%b);
}

• 点赞
• 写回答
• 关注问题
• 收藏
• 复制链接分享

#### 2条回答默认 最新

• 已采纳
小灸舞 2016-04-10 13:57

有两个问题：
1.Fraction p3("12,14");不能这样，因为"12,14"是常量字符串，strtok企图修改常量区就会报异常，要改成栈区或者堆区的字符数组或者字符串
2.p1 = strtok(s,"/,");和p2 = strtok(NULL,"/,");楼主加一个/要干嘛？就算转义也应该是\,而且,是不用转义的
改成p1 = strtok(s,",");p2 = strtok(NULL,",");

`````` #include <iostream>
using namespace std;
class Fraction
{

private:
int num, den;
public:
Fraction(char s[10]);
void set(int n, int d){ num = n; den = d;normalize(); }
int get_x(){ return num; }
int get_y(){ return den; }
private:
void normalize();
int lcd(int a,int b);
};
int main()
{
char str[10] = "12,14";
Fraction p3(str);
cout << p3.get_x() << endl;
cout << p3.get_y() << endl;
system("pause");
return 0;
}
Fraction::Fraction(char s[])
{
int n = 0;
int d = 1;
char *p1,*p2;
p1 = strtok(s,",");
p2 = strtok(NULL,",");
if (p1 != NULL)
{
n = atoi(p1);
}
if (p2 != NULL)
{
d = atoi(p2);
}
set(n, d);
}
void Fraction::normalize()
{
if (num == 0 || den == 0)
{

num = 0;
den = 1;
}
int n = lcd(num,den);
num /= n;
den /= n;
}
int Fraction::lcd(int a,int b)
{
if (b == 0)
{

return a;
}
else return lcd(b,a%b);
}
``````
点赞 1 评论 复制链接分享
• Fraction p3("12,14");
->
char s[100]="12,14";
Fraction p3(s);

点赞 2 评论 复制链接分享