C++ 通过使用 argc 和 argv 读取文本文件

c++ by using argc and argv read the text file

本文关键字:argv 读取 取文本 文件 argc C++      更新时间:2023-10-16
////////// 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 来读取文件:数字.txt(里面的数字很少(。我的目标是:在终端中读取带有我的 ./sort 的文件,例如:./sort numbers然后使用缓冲区和索引来计算里面有多少个数字,使用索引创建动态数组,最后我再次读取文件,但使用 atoi 将所有"数字"更改为 int。

我在终端中键入:./排序数字后出现分段错误:11。

谁能在这里帮我? 我需要这些数组来对我的数字进行排序。到目前为止,我得到了:

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;
    }
char *buffer[3];

创建指向字符的三个指针的数组。它不会分配任何要指向的存储。它不会分配任何要指向的存储。这些指针可以指向任何内容。有效的记忆,无效的记忆,你哥哥的色情藏匿处,你不知道。如果幸运的话,它们会指向无效的内存,您的程序将崩溃。

fin >> *buffer;

尝试将从文件读取的字符串放入上面三个指针中的第一个指针所指向的内存中。由于我们不知道它们指向何处,因此我们不知道文件中的输入将写入何处。很有可能它会尝试写入无效内存并且程序崩溃。

若要解决此问题,请分配一些存储,将指针指向此存储,然后读入指针。

例如。

char *buffer[3];
char storage[128];
buffer[0] = storage;

然后后来

fin >> *buffer;

也就是说,我认为这根本不是你想要的。更有可能

char *buffer[3];

应该是

char buffer[3];

在这种情况下

fin >> *buffer;

只将文件中的一个字符读取到缓冲区中,所以这可能也是一个错字和

fin >> buffer;

是有意为之。警告!!!如果从 fin 读取的字符串超过 2 个字符,则可能仍会崩溃。你可能想重新考虑一下。

如果允许,请使用 std::string 和 std::vector,但鉴于现在还处于学期初期,您的教师可能希望通过让您用石头击打东西并可能将树枝摩擦在一起来生火来教您代码。