【发布时间】:2015-12-31 06:28:46
【问题描述】:
////////// new update!!!!! //////////
.txt 有 15 个数字,最后一个数字是“15” 1. 我尝试计算我的 .txt 文件中有多少(保存到我的索引中)数字。 2. 使用索引创建我的动态数组大小。 3. 将所有数字保存到我的动态数组中。
问题:如何将char动态数组覆盖为int动态数组。
我的终端输出垃圾:
Open sucessues!!
index: 15
buffer: 15
0
1073741824
0
1073741824
2136670223
32767
-1680479188
32767
0
0
0
0
0
0
0
int main(int argc, char* argv[])
{
char *nPtr = argv[1];
char *buffer = new char[5];
int index = 0;
ifstream fin(nPtr); //open the file
if (argc > 1){
// allocate the memory
if(!fin){
cout << "can't read the file!!" << endl;
return -1;
}
if(fin){
cout << "Open sucessues!! " << endl;
}
while (!fin.eof()){
fin >> buffer;
index++; //counting here!!!
}
cout << "index: " << index << endl; //print out the counting results!
cout << "buffer: " << buffer << endl; // checking the last number! should "15"
delete[] buffer; //
buffer = NULL;
int *number = new int[index];
char *temp = new char[index];
int *home = number; //home
while(!fin.eof()){
fin >> temp;
*number= atoi(temp); //im confessing right here!!!
number++;
temp++;
}
number = home;
for (int i = 0; i < index; ++i)
{
cout << *number << endl; //*number print out garbage, i don't know why!
number++;
}
fin.close( );
}
return 0;
}
/////************
//////// 旧的 ///////// 不读 ///// 我想知道如何使用 argc 和 argv 来读取文件: numbers.txt(few numbers里面)。 我的目标是:在终端中使用我的 ./sort 读取文件,例如: ./sort numbers 然后使用缓冲区和索引计算里面有多少个数字,使用索引创建动态数组,最后我再次读取文件,但使用atoi将所有“数字”更改为int。
我在终端中输入:./sort numbers。
有人可以帮我吗?我需要这些数组来对我的号码进行排序。 到这里为止:
int main(int argc, char* argv[])
{
char *nPtr = argv[1];
char *buffer[3];
int index = 0;
ifstream fin(nPtr); //open the file
// allocate the memory
if(fin.is_open()){
cout << "open" << endl;
while(!fin.eof()){
fin >> *buffer;
index++;
}
cout << index << endl;
}
【问题讨论】:
-
在索引到
argv之前,您需要检查argc。验证用户是否向您的程序提供了正确数量的参数。 -
请不要添加无关的语言标签。爪哇?? C??
-
您只为
buffer分配了 3 个字符。如果fin中有超过 3 个字符,您将覆盖缓冲区 -- 未定义行为(可能是崩溃)。 -
写入取消引用未初始化指针导致分段错误
标签: c++