本文介绍了字符串或字符到整数问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 有人能告诉我下面的代码片段有什么问题吗? char a = x [index]; char b = y [index ]; int result = strtol(& a,NULL,10)+ strtol(& b,NULL,10); 我得到了结果使用result = atoi(& a)+ atoi(& b); cout<< a<< ''\t''<< b<< ENDL;显示a和b的值是正确的。 cout<< atoi(& a)(或strtol(& a,NULL,10))是正确的但是atoi(& b)和 strtol(& b,NULL,10)是不正确的。 这个项目假设采用无限制的整数。大小并添加它们。 Mandrake Linux 10,gcc-c ++ - 3.3.2-6mdk,内核2.6.3-15mdkCan anyone tell me what is wrong with the following code fragment?char a = x[index];char b = y[index];int result = strtol(&a, NULL, 10) + strtol(&b, NULL, 10);I got the same result using result=atoi(&a)+atoi(&b);cout << a << ''\t'' << b << endl; shows the values of a and b to be correct.cout << atoi(&a) (or strtol(&a, NULL, 10)) is correct but atoi(&b) andstrtol(&b, NULL, 10) are incorrect.This project is suppose to take integers of "unlimited" size and add them.Mandrake Linux 10, gcc-c++-3.3.2-6mdk, kernel 2.6.3-15mdk推荐答案 strtol没有指向单个char的指针。很少有事情可做; 当你看到(char *)你通常可以认为它是一个指向 字符数组的指针,并且通常是零终止的字符串。 无论如何使用strtol转换单个字符串都是愚蠢的,只需减去 ''\ 0''。strtol does not take a pointer to a single char. Very few things do;when you see (char *) you can usually assume that it is a pointer to anarray of chars, and most often a zero-terminated string.Using strtol to convert a single char is silly anyway, just subtract''\0''. strtol不会指向单个char。很少有事情可做; 当你看到(char *)时,你通常会认为它是指向一组字符的指针,通常是一个以零结尾的字符串。 ''\'''。 strtol does not take a pointer to a single char. Very few things do; when you see (char *) you can usually assume that it is a pointer to an array of chars, and most often a zero-terminated string. Using strtol to convert a single char is silly anyway, just subtract ''\0''. 我不确定关于减法你想说什么。 无论如何,我通常使用atoi()将一个字符(或字符串)转换为 整数。可能有更好的方法来做我想做的事情但是这个 无论如何都是初稿。我需要能够添加2个大于/或的大整数,而不是存储在无符号长整数中。 事实证明,在我的系统上,任何整数类型使用4个字节(根据 从sizeof()返回)。无论如何,我正在输入值作为字符串和 将它们存储在一个向量中。 此外,我仍然需要知道为什么第一次调用strtol()返回 正确值,而第二次调用strtol()则没有。I''m not sure of what you''re trying to say about the subtraction.Anyway, I normally use atoi() to convert a character (or string) to aninteger. There''s probably a better way to do what I''m trying to do but thisis a first draft anyway. I need to be able to add 2 large integers that arelarger than can be stored in an unsigned long.As it turns out, on my system, any integer type uses 4 bytes (according tothe return from sizeof()). Anyway, I''m entering the values as strings andstoring them in a vector.Besides, I still need to know why the first call to strtol() returns thecorrect value while the second call to strtol() doesn''t. 这取决于偶然发生在内存中跟踪变量的情况。 /> 第一个和第二个仍然同样错误。It depends on what happens by chance to follow the variable in memory.Both the first and thee second are still equally wrong. 这篇关于字符串或字符到整数问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
07-11 05:40