【发布时间】:2015-01-11 20:16:38
【问题描述】:
我正在尝试使用 atoi 函数将存储在 argv 数组中的 char 转换为 int,我 我是 C++ 和传递参数的新手,所以请多多包涵。
每次我尝试将 atoi[1] 中存储的值设置为 const char 并打印该 char 时,它根本不会打印任何内容。如果我做错了,它仍然应该打印一个内存地址,对吧?
我将它设置为 const char 因为 atoi 函数需要一个 const char 作为它的参数。 (如有错误请指正)
我一直通过 ideone.com 执行此操作,因此我的 argv 数组并未真正在运行时设置,因为 ideone 不允许这样做。
到目前为止,这是我的代码:
#include <iostream>
#include<string>
#include <stdlib.h>
using namespace std;
int main() {
int argc;
char *argv[4];
*argv[0] = 'x';
*argv[1] = '5';//this will be the length of our first array for testing
*argv[2] = '3';//this will be the length of our second array for testing
*argv[3] = '4';//this will be the length of our third array for testing
argc = 4;
const char * argv1 = argv[1];
cout << "*argv[1]: " << *argv[1] << endl;
cout << "argv[1]: " << argv[1] << endl;
cout << *argv1;
//int x = atoi(argv1);
return 0;
}
更新的代码:现在具有编译功能!
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
int main() {
char nullGuy = NULL;
char * nullptr1 = &nullGuy;//Null ptr
int argc;
const char * argv[5];
argv[0] = "x";
argv[1] = "5";
argv[2] = "3";
argv[3] = "4";
argv[4] = nullptr1;
argc = 4;
int x = atoi(argv[1]);
cout << "argv[1]: " << argv[1] << endl;
cout << "x: " << x << endl;
return 0;
}
【问题讨论】:
标签: c++