将函数从WCHAR_T数组转换为long int
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' ') {
//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。
相关文章:
- 在C++中使用GDAL可以将图像的像素坐标转换为lat,long吗
- 错误:隐式转换更改符号:'int'到'unsigned long'
- 从 long 转换C++位集构造函数的复杂性是多少?
- C++11 模板函数"implicity"将位集<N>转换为"unsigned long"
- 替换 c++ 中的 c 样式强制转换 (long&)
- 如何在<typename> <long> 不更改给定代码的情况下将自定义向量与 STL 向量相互转换?
- 隐式转换会丢失整数精度:'long' 到 'int'
- 为什么 int 到长 long int 的隐式转换在 C++ 中给出了意想不到的答案?
- 是否允许在模板专用化时从int转换为long(应该编译此代码)
- 将long-long的数组转换为字符串
- C++11自动.从float转换为long
- C++ 将 int 转换为 *LONG
- 将函数从WCHAR_T数组转换为long int
- 将无符号字符数组强制转换为long-long
- 将 QByteArray 转换为“long”会为相同的输入输出不同的结果
- 如何将双精度转换为标准'long double'
- 将C++字符串变量转换为long
- 为什么从无符号long-long转换为double会导致数据丢失
- C++无法将'long double'转换为'long double*',因为参数'1'为"long
- 在C++中,将double转换为long的类型返回了不正确的值