字符中的奇怪字符

时间:2013-08-30 19:45:55

标签: c++

所以该程序应该做什么:通过键入restrict限制应用程序在mac上打开。它应该允许通过使用与以前相同的名称再次键入restrict来访问应用程序。

该程序正在做什么:限制应用程序工作正常。但是当我再次输入restrict时,会出现以下输出:

CandyBar
\277_\377CandyBar
\277_\377Restricting application
chmod: /Applications/CandyBar
\277_\377.app: No such file or directory
chown: /Applications/CandyBar
\277_\377.app: No such file or directory
chmod: /Applications/CandyBar
\277_\377.app: No such file or directory

正如您所看到的,它在字符串末尾添加了字符\277_\377。这是我的源代码:

for (int i = 0; strlen(argument) + 14 >= i; i++) {
    argument[i] = '\0';
}
cout << argument;

getArguments();
argument[strlen(argument) - 1] = '\0';
cout << argument;
string application(argument);
cout << application;
if (!restrictedApplication[application]) {
    restrictedApplication[application] = false;
}
if (restrictedApplication[application] == false) {
    cout << "Restricting application\n";
    restrictedApplication[application] = true;
    string fullCommand =
        "chmod -x '/Applications/" + application + ".app';" + 
        "chown root '/Applications/" + application + ".app';" + 
        "chmod 000 '/Applications/" + application + ".app'";
    char fullCommandChar[256];
    for (int i = 0; fullCommand[i] != '\0'; i++) {
        fullCommandChar[i] = fullCommand[i];
    }
    system(fullCommandChar);
}
else {
    cout << "Restoring application\n";
    restrictedApplication[application] = false;
    string fullCommand =
        "chmod +x '/Applications/" + application + ".app';" +
        "chown jamespickering '/Applications/" + application + ".app';" +
        "chmod 777 '/Applications/" + application + ".app'";
    char fullCommandChar[256];
    for (int i = 0; fullCommand[i] != '\0'; i++) {
        fullCommandChar[i] = fullCommand[i];
    }
    system(fullCommandChar);
}

2 个答案:

答案 0 :(得分:5)

这可能是因为它在字符串末尾寻找\0字符,但它从未收到它。

我还没有深入研究你的代码,但我发现你正试图在这里做到这一点。

argument[strlen(argument) - 1] = '\0';

当我找到\0发生错误的地方时,我会编辑我的帖子,因为这就是产生奇怪的内容

\277_\377输出。


编辑:

for (int i = 0; strlen(argument) + 14 >= i; i++) {
     argument[i] = '\0';
}

你想用这部分代码做什么?

这实际上是循环并将\0index 0添加到length of the string plus 14到参数。这应该通过参数的数组大小,对吗?有人可以解释这甚至可以显示输出吗?

答案 1 :(得分:1)

下面:

for (int i = 0; strlen(argument) + 14 >= i; i++) {
    argument[i] = '\0';
}
cout << argument;

您将argument的第一个元素设置为0,然后尝试输出它。你究竟要输出什么?你这样做时就清空了字符串。

相关问题