简体   繁体   English

将char转换为int in C,然后将值printf为int?

[英]Convert char to int in C and then printf the value as int?

I keep getting these strange negative values when I run the code. 运行代码时,我不断得到这些奇怪的负值。 Does anyone know what they are and how to get just an int (For example 10, 20, 8...)? 有谁知道它们是什么以及如何获得一个整数(例如10、20、8 ...)? Why do I always get a different and wrong value? 为什么我总是得到不同的错误值? When I run the code with arguments 2 and 3 it should output 10... 当我使用参数2和3运行代码时,它应该输出10 ...

int main(int argc, char *argv[]) {
  int h;
  int a;
  int b;
  a = (int) argv[1];
  b = (int) argv[2];
  if (argc == 3) {
    h = 2 * (a + b);
    printf("The perimeter of the rectangle is %d\n", h);
  } else {
    fprintf(stderr, "Usage: %s <arguments>\n", argv[0]);
  }
}

Output:
The perimeter of the rectangle is -1874251136
or
The perimeter of the rectangle is -1424723328
or
The perimeter of the rectangle is -940059169

Test too late 测试为时已晚

if(argc==3){ tests for required argc , but unfortunately after using argv[1], argv[2] . if(argc==3){测试所需的argc ,但不幸的是,在使用argv[1], argv[2] Move test before and exit if not as needed. 先进行测试,然后根据需要退出。 Note: good use of error message to stderr . 注意:正确使用错误消息给stderr

if (argc != 3) {
  fprintf(stderr,"Usage: %s <arguments>\n", argv[0]);
  return -1; // or return EXIT_FAILURE
}  

Incorrect conversion 转换错误

Code is converting the pointer and not the referenced text. 代码正在转换指针,而不是被转换的文本。

#include <stdlib.h>

// a = (int)argv[1];
a = atoi(argv[1]);

Robust code would use strtol() or perhaps roll your own `strtoi()' 健壮的代码将使用strtol()或滚动您自己的`strtoi()'

argv is an array of pointers to char . argv是一个指向 char指针数组。 Ie it's an array of strings . 也就是说,它是一个字符串数组。 The string "1" is not equal to the integer 1 (or even the character '1' ). 字符串"1" 等于整数1 (甚至等于字符'1' )。 The fact that you're doing a cast should almost always be a red flag. 您正在进行演员表转换的事实几乎总是危险的一面。

To convert a string to a number use the strtol function. 要将字符串转换为数字,请使用strtol函数。

And always remember to check argc before accessing argv . 并且始终记得访问argv 之前检查argc

b = (int)argv[2]

The (int) is a cast of the pointer value -- it just converts the type (int)是指针值的强制转换-它只是转换类型

Instead try use atoi or strtol to convert a string to an integer value. 而是尝试使用atoistrtol将字符串转换为整数值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM