【问题标题】:C++ Resetting system commandsC++ 重置系统命令
【发布时间】:2013-09-07 03:52:14
【问题描述】:

代码

while (dataFile)
    {
        getline(dataFile, input, '$');
        if (getenv("windir"))
        {
            cmd = "open -a 'Google Chrome' http://www.dictionary.reference.com/browse/" + input;
        }

        else
        {
            cmd = "open -a 'Safari' http://www.dictionary.reference.com/browse/" + input;
        }
        system(cmd.c_str());
        cmd.erase(cmd.find(input));
        cout << cmd;
    }

当 .txt 文件中有多个单词时,它只会查找第一个单词,而不能查找其他单词。它在输出sh: line 2: WORD: command not found 中说明了这一点。我怎样才能让它重置命令,以便其他词起作用?

cmd和input的初始化在main方法里面。

 string cmd;
 string input;

这是文本文件的样子:

Word1
Word2
WordETC

【问题讨论】:

  • 你的意思是一行中有多个单词,还是有多个单词的行?
  • @jmstoker 多行。每行一个单词,否则程序根本无法运行,因为它的意思是每行读取一个单词。
  • input的类型是什么?
  • 另外,查看cmd 的声明也会有所帮助。
  • @mattbat131 你为什么用$而不是\n定界?

标签: c++ string input system text-files


【解决方案1】:

我不能代表 Safari 路径,我假设在 OSX 或类似系统中,但在 Windows 7 上,以下代码将在 Google chrome 中打开一个新选项卡

#include <iostream>
#include <fstream>
#include <string>

using namespace std;


int main()
{
    std::ifstream dataFile("C:\\test.txt", std::ifstream::binary);

    string input;
    std::string cmd;

    // This path will depend on the operation system
    std::string googlePath = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe";        

    while (dataFile)
    {
        getline(dataFile, input, '\n'); // use \n for endline

        if (getenv("windir"))
        {
            cmd = "cmd /C start \"" + googlePath + "\" http://www.dictionary.reference.com/browse/" + input + " --newtab";
        }

        else
        {
            cmd = "open -a 'Safari' http://www.dictionary.reference.com/browse/" + input;
        }
        system(cmd.c_str());
        cmd.erase(cmd.find(input));
        cout << cmd;
    }

    return 0;
}

test.txt

turtle\r\n
dove\r\n
shoulder

【讨论】:

  • 选项卡不是问题,只是当程序尝试使用不同的单词再次运行命令时,它无法工作。我觉得当它再次循环循环时,它没有正确重置命令,它只是使用命令这个词。
  • 这是在 Windows 还是其他操作系统上?上面的代码每次都能得到正确的 Windows 命令。
  • 我在 Mac 上使用它。我让程序检查操作系统是否是 Windows 的原因是因为如果我运行这个程序并在 google chrome 上设置它会打开并行,我并不总是希望发生这种情况。
猜你喜欢
  • 1970-01-01
  • 2011-09-24
  • 2014-10-06
  • 1970-01-01
  • 2012-09-13
  • 1970-01-01
  • 2014-07-18
  • 1970-01-01
  • 2011-11-19
相关资源
最近更新 更多