我正在尝试将 int 值插入字符串,而不是 1,我得到 10

I am trying to insert int values into string and instead of 1 i get 10

本文关键字:插入 int 字符串      更新时间:2023-10-16

我有 1005 个节点,所以我在这里输入 1005 和值 1 到 1005 通过循环 即使我手动输入,我也得到相同的打印

void call() 
{
int x;
cout << "Enter Number of characters";       string s;
cin >> t;
cout << "Enter char names :";
for (int i = 0; i < t; i++) 
{
x = i + 1;
str1 = to_string(x);
//cin >> str1;
insertd(str1);
}
}

void insertd(string n) {
node *ptr = new node;
ptr->name = n;
if (head == NULL) {
head = ptr;
last = ptr;
}
else {
last->down = ptr;
last = ptr;
}
}

当我在这里使用此部分打印时

void print() {
current = head;
node *p;
while (current != NULL) {
p = current;
while (p != NULL) {
cout << p->name << p->weight << "   ";
p = p->next;
}
cout << endl;
current = current->down;
}
}

我得到的结果是 10,20,30 而不是 1,2,3

如果您使用 std::to_string 进行转换,则不应打印 10 而不是 0。 您可以尝试仅打印名称吗?

std::cout << p->name << std::endl

你的p->权重肯定为0。