gpt4 book ai didi

c++ - 关于从字符数组转换为字符串的问题 - C++

转载 作者:行者123 更新时间:2023-11-28 02:11:23 27 4
gpt4 key购买 nike

#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main () {
string vet[10], aux;
std::vector<char> name;
int count=0, sum=0;

while (count<10) {
getline(cin, aux);

for (int i=0; i<aux.length(); i++) name.push_back(aux[i]);

for (int i=0; i<name.size(); i++) {
name[i] = tolower(name[i]); //para garantir que todos os caracteres estão em minúsculo
if (name[i] > 96 && name[i] < 123 && name[i] == 32) //faixa de decimais das letras minúsculas e espaço em caso de nome composto
sum += name[i];
}

char v[name.size()]; //vetor auxiliar criado para realizar a conversão de vetor de char para string

for (int i=0; i<name.size(); i++) {
v[i] = name[i];
}

while (vet[sum%10] != "\0") //para evitar colisão
sum++;

vet[sum%10] = (string) v; //conversão para string e => K mod m = K % m em C++
cout << vet[sum%10] << endl;
count++;
sum = 0;

for (int i=0; i<name.size(); i++) v[i] = '\0';

name.clear();
}

cout << endl;

for (int i=0; i<10; i++) cout << vet[i] << endl;

return 0;
}

此代码使用散列概念将名称存储在数组中。

我的问题是:

Everytime that I try to insert a name with 8, 16 or 24 characters, while converting from char array to string, the compiler always put another 3 characters in front of them. If I try a name with 9, 17 or 25 characters, the compiler always put another 2 characters in front of them. And if I try a name with 10, 18 or 26 characters, the compiler always put another character in front of them.

Why does it happens? Is there a way to prevent it?

我需要所有名称都与它们插入输入时完全相同(但小写),但根据哈希逻辑排序。

提前致谢!

最佳答案

问题出在这里:

char v[name.size()];

正如所指出的,这不是标准的 C++ ...

无论如何,您可以像这样修复它:

std::string v;    
v.resize(name.size());

或多或少,它与您的 char 数组具有相同的效果,只是它不使用 char 数组。

关于c++ - 关于从字符数组转换为字符串的问题 - C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35555200/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com