返回信息流这是编译原理留的作业,词法分析。我现在大概就是分析过后确定是个标识符,存到链表里面,然后输出。可是在调试的时候发现。运行到红色语句的时候,对tmpSign这个string进行修改,我链表中的first->id也进行修改,这是为什么呢?难道是指向同一内存?那么string该怎么复制?
谢各位大神~~
附代码:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct sign{
string id;
struct sign * next;
};
struct sign * first= NULL, * last = NULL;
int total = 0;
bool isCharacter(char a);
bool isDigit(char a);
void add(string a);
void handleWord(string a);
void showSign(void);
int main(int argc, char *argv[])
{
cout << "Please input the name of the file." << endl;
string name;
cin >> name;
ifstream source(name.c_str());
if (!source.is_open()){
cout << "Fail to open the file!";
exit(1);
}
string buffer;
char temp;
int count = 0;
while (!source.eof()){
getline(source,buffer);
count = 0;
temp = buffer[count++];
while(temp != '\0'){//处理一个单词
if(isCharacter(temp)){
string tmpSign;
int cur = 0;
while((temp != ' ') && (temp != '\0')){//读取这个单词,循环的时候对tmpSign赋值,就发生错误了。。。
tmpSign[cur++] = temp; temp = buffer[count++];
}
tmpSign[cur] = '\0';
handleWord(tmpSign);
}else if(isDigit(temp)){
string num;
int cur = 0;
while(isDigit(temp)){
num[cur++] = temp;
temp = buffer[count++];
}
num[cur] = '\0';
add(num);
}else{
//其他情况
}
}
}
}
showSign();
return 0;
}
bool isCharacter(char a){
if((a >= 65 && a <= 90)||(a >=97 && a <=122))
return true;
else
return false;
}
bool isDigit(char a){
if(a >= 48 && a <= 57)
return true;
else
return false;
}
void handleWord(string a){
for(int i = 0; a[i] != '\0'; i++)
if(!(isCharacter(a[i]) || a[i] == '_' || isDigit(a[i]))){
cout << "Illegal input!" << endl;
return;
}
add(a);
}
void add(string a){
if(first == NULL){
first = new struct sign;
first -> id = a;
first -> next = NULL;
last = first;
}else{
struct sign * tempp = new struct sign;
tempp -> id = a;
tempp -> next = NULL;
last -> next = tempp;
last = tempp;
}
}
void showSign(void){
struct sign * tep = first;
cout << "Here are the signs." << endl;
while(tep != NULL){
cout << tep -> id << endl;
tep = tep -> next;
}
}
这是一条镜像帖。来源:北邮人论坛 / cpp / #83410同步于 2014/10/18
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖
【问题】关于C++ string复制的问题?
x435290622
2014/10/18镜像同步4 回复
订阅后,新回复会通过你的通知中心匿名送达。
4 条回复
没有啊,我单步调试的时候 tmpSign都是我想要的值。
只是修改tmpSign的时候,链表也跟着修改
【 在 ashjn2011 的大作中提到: 】
: 你赋值的时候tmpSign,长度为0,不能够用数组运算符
: 用 tmpSign += temp 就好了
你在给tmpSign赋值时就已经出错了,因为tmoSign 的size为0
参见:std::string::operator[] (http://www.cplusplus.com/reference/string/string/operator[]/)
Exception safety
If pos is not greater than the string length, the function never throws exceptions (no-throw guarantee).
Otherwise, it causes undefined behavior.
【 在 x435290622 的大作中提到: 】
: 没有啊,我单步调试的时候 tmpSign都是我想要的值。
:
: 只是修改tmpSign的时候,链表也跟着修改
非常感谢!!!按照你说的办法真的成功了!多谢!
【 在 ashjn2011 的大作中提到: 】
: 你在给tmpSign赋值时就已经出错了,因为tmoSign 的size为0
: 参见:std::string::operator[] (http://www.cplusplus.com/reference/string/string/operator[]/)
: Exception safety
: ...................