C ++重置系统命令

时间:2013-09-07 03:52:14

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

代码

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和输入的初始化在main方法中。

 string cmd;
 string input;

这就是文本文件的样子:

Word1
Word2
WordETC

1 个答案:

答案 0 :(得分:0)

我不能代表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