【发布时间】:2018-05-24 13:20:44
【问题描述】:
嗨,我在尝试将一行数字(例如:100 101 102)转换为(stoul)动态分配的无符号整数时遇到问题;预期的是,我可以在可变长度输入中逐个数字地访问数组。
#include <iostream>
#include <new>
#include <string> //Memset
int console(){
std::string console_buffer;
unsigned long int* integersConverted = NULL;
unsigned int integersNumberOf = 0;
for( ; ; ){
std::getline(std::cin, console_buffer);
integersConverted = console_defaultSyntaxProcessing(console_buffer, &integersNumberOf);
std::cout << "Found the following integers from conversion: ";
for(unsigned int debug_tmp0 = 0; debug_tmp0 < integersNumberOf; debug_tmp0++){
std::cout << integersConverted[debug_tmp0] << " ";
std::cout << std::endl;
}
delete integersConverted;
integersConverted = NULL;
}
return 0;
}
unsigned long int* console_defaultSyntaxProcessing(std::string console_buffer, unsigned int* integersNumberOfUpdate){
*integersNumberOfUpdate = 0;
unsigned int integersNumberOf = 0;
unsigned long int* integersFound = NULL;
integersFound = new unsigned long int(sizeof(unsigned long int) * 1024);
std::size_t stringPosition = 0;
for( ; stringPosition < console_buffer.length() && integersNumberOf < 1024; ){
integersFound[integersNumberOf] = std::stoul(console_buffer, &stringPosition, 10); //10 = Decimal
integersNumberOf++;
}
*integersNumberOfUpdate = integersNumberOf;
return integersFound;
}
如果我只输入一个数字,我会得到正确的值,但是如果我输入两个或更多数字并且所有位置都得到第一个整数,则会打印整个 1024 数组。我试图手动将函数 std::string 设置为常量,将 console_buffer.length() 归零,以便找到'\0'等;不幸的是没有工作..
UPDATE --- 主题首次发布后 5 分钟; 正如 Yashas 所回答的,问题在于 console_defaultSyntaxProcessing for 循环; stoul &stringPosition 返回读取的字符数,而不是 std::string 的位置。 使用 stoul 的另一个问题是,如果我输入 100(101,它不起作用,所以遵循固定代码但不应使用。 正如 lamandy 建议的那样,请改用 std::stringstream。
std::size_t stringPosition = 0;
std::size_t stringPositionSum = 0;
for( ; stringPosition < console_buffer.length() && integersNumberOf < 1024; ){
try{
integersFound[integersNumberOf] = std::stoul(&console_buffer[stringPositionSum], &stringPosition, 10);
integersNumberOf++;
stringPositionSum = stringPositionSum + stringPosition;
}
catch(std::exception& exception){
break;
} //This catch will be used constantly by this buggy code.
【问题讨论】:
-
所有的指针都有点吗?然而你通过值传递 std::string。
-
我试过通过指针传递,它也没有工作。指针: integersNumberOf_Update 是直接在 console() 上更改值,就像 stoul 对 size_t 参数所做的那样。 integersFound 必须动态分配,因为整数的数量可能非常大。 integersConverted 只是接收指向 integersFound 的指针。