为 git 存储库制作 c 文件

Making a c file for a git repository

本文关键字:文件 git 存储      更新时间:2023-10-16

我对 Ubuntu 和 PuTTY 非常陌生,并在其中放入了一个C++文件,但我的C++文件遇到了问题。我需要程序做的是从 Ubuntu 端输入一个字符串,放入C++程序中,让它计算输入了多少个字符串,然后像这样发回:

./myfile Supplying arguments now
Argument #0: ./myfile
Argument #1: Supplying
Argument #2: arguments
Argument #3: now
Number of arguments printed: 4

所以,当我在下面运行我的程序时,程序会永远持续下去,我无法逐步完成它。是什么原因造成的,为什么和/或我可以做些什么来解决问题?

#include <stdio.h>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
    int count = 0;
    while (*argv[argc] != NULL)
    {
        count++;
    }
    cout << count << endl;
    system("PAUSE");
    return 0;
}

你的代码是一个无限循环,因为你的while循环总是检查相同的条件。这是因为argc永远不会更改代码。

你想写的是while (*argv[count] != NULL).但是,你的意思也不正确。

  1. C 不检查数组边界。当您读取超过数组边界时,您不一定会遇到 0 值。您将读取该位置内存中的随机垃圾数据。
  2. 您无需自己计算参数的数量,因为您已经在变量 argc 中拥有它。

因此,迭代所有命令行参数的更好解决方案是一个for循环,它将count0递增到argc