将函数从WCHAR_T数组转换为long int

Convert function from wchar_t array to long int

本文关键字:转换 long int 数组 函数 WCHAR      更新时间:2023-10-16

我正在编写一个将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'') {
    //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-character终止。文件中的管道可能会用newline结束字符串,然后将其null结束。结果,您将" r"answers" n"计为数字,从中减去0'并相应地增加功率。

请尝试std::wcout << wchartol(L"30 237 740rn") << 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;
  }
}

(免责声明:我没有测试此代码,所以出于自身风险)

此循环是错误的

while(*firstArray != L'')
{
    firstArray++;
    if(*firstArray == L' ')continue;
    count++;
}

由于您在字符串开始时要进行测试之前要增加,因此找不到。我认为你的意思是这个

while(*firstArray != L'')
{
    if(*firstArray++ == L' ')continue;
    count++;
}

为什么不使用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。