[英]Convert function from wchar_t array to long int
我正在编写一个将wchar_t
数组转换为long integer
数值的函数(该函数将忽略空格beetwen digits)。 看我的代码:
long wchartol(wchar_t *strArray, long retVal = 0) {
wchar_t *firstArray = strArray;
long pow;
int count, i;
count = 0;
i = 0;
pow = 1;
while(*firstArray != L'\0') {
//firstArray++;
if(*firstArray++ == L' ')continue;
count++;
}
firstArray--;
while(i < count) {
if(*firstArray != L' ') {
retVal += (*firstArray - L'0') * pow;
pow*=10;
i++;
}
firstArray--;
}
return retVal;
}
我还有一个有趣的问题:当我从某个文件复制数字数据(包含空格)并将其粘贴到函数的参数中时,该函数返回的数据错误; 但是,当我用键盘上键入的空格替换这些空格时,一切都很好。 什么原因? 我以这种方式调用该函数:
std::wcout << wchartol(L"30 237 740") << std::endl;
读取使用outputstream.imbue(std::locale::global(std::locale("")));
编写的文件 也许那是原因吗?
您的代码假定输入字符串仅由数字和空格组成,并以空字符终止。 文件中的管道传递可能会将字符串以换行符结尾,然后为null。 结果,您将'\\ r'和'\\ n'视为数字,从它们中减去'0'并相应地增加功率。
请尝试std::wcout << wchartol(L"30 237 740\\r\\n") << std::endl;
看看是否产生相同的错误值。
编辑:这是一些没有对字符串做任何假设的代码,如果将字符串中的第一个整数连接起来,它将仅忽略任何空格。 它将指针设置到第一个字符之后的位置,该字符既不是数字也不是空格,并将所有数字从那里连接到字符串的开头:
// move pointer to position after last character to be processed
while( (*firstArray >= L'0' && *firstArray <= L'9')* ||
*firstArray == L' ')
firstArray++;
// process all digits until start of string is reached
while(firstArray > strArray) {
firstArray--;
if(*firstArray >= L'0' && *firstArray <= L'9') {
retVal += (*firstArray - L'0') * pow;
pow*=10;
}
}
(免责声明:我没有测试此代码,因此使用风险自负)
为什么不只使用wstringstream?
wifstream in(...);
wstringstream ss;
wchar_t ch;
in >> ch;
while (in)
{
if (ch != L' ')
ss << ch;
in >> ch;
}
long number;
ss >> number;
至于文件的问题,可能是文件的编码不是Unicode。 尝试使用文本编辑器打开文件,并告诉它将文件存储为Unicode。
这个循环是错误的
while(*firstArray != L'\0')
{
firstArray++;
if(*firstArray == L' ')continue;
count++;
}
因为您在测试之前先递增,所以不会在字符串开头找到空格。 我想你是这个意思
while(*firstArray != L'\0')
{
if(*firstArray++ == L' ')continue;
count++;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.