有没有一种方法可以从cmd字符串中复制字符串?

3

我完全是编程新手,需要一位老手的建议,因为这是我任务的一部分。

有没有办法读取由命令提示符(CMD)生成的字符串?

我的任务是创建一个代码来ping所有网络并通过文件的输入/输出将IP地址分配为活动和非活动状态。

我想复制cmd中的字符串,例如:

来自192.168.0.1的回复:字节=32时间<1ms TTL = 64 <- (这表示活动) 来自192.168.0.2的回复:目标主机不可达 <- (这表示非活动)

如果我能够复制那一行,我就可以编写If / Else条件来将它们分开。如果有任何更简单的方法来改善这种情况,请协助我。谢谢。

下面的代码是为了ping所有IP地址直到255,但我仍然需要另外一个函数来区分活动和非活动IP地址。

    using namespace std;

    void main()
    {
    string ipAddress;

    cout << "Enter the IPv4 address network..." << endl;
    cout << "Example: 10.0.0. or 192.168.1." << endl;

    getline(cin, ipAddress);
    cout << "Please wait..." << endl;

    string s = "ping " + ipAddress;

    for (int x = 0; x <= 255; ++x)
            {
                    stringstream ss;
                    ss << x << endl;
                    string newString = ss.str();
                    string finalString = s + newString;

                    system(finalString.c_str());
            }

    system("pause");
    }

附言:我也在 http://www.cplusplus.com/forum/beginner/196197/ 上发布了文章。


你想要捕获std::system()命令的输出吗? - Galik
3个回答

1

这对OP来说行不通。他明确提到了“CMD”,这是MS Windows命令行shell。他需要使用_popen(注意前导下划线),https://msdn.microsoft.com/en-us/library/96ayss4b.aspx是规范的链接。 - Martin Bonner supports Monica

0

如果出于某种原因您不想使用_popen(),还有另一种替代方法:
您可以使用>filename语法将ping的输出重定向到文件中。

例如,std::system("ping 8.8.8.8 >out.txt")将调用ping并将其输出写入out.txt

此功能是Windows shell本身的一部分,因此它将与任何程序一起使用。


0

enter image description here

这里有另一种从CMD复制的方法。

以下代码使用内置函数system()启动Windows自带的ping.exe

system("ping www.google.com > ping.txt ")

并将控制台屏幕上的输出重定向到文本文件中。

ping www.google.com > ping.txt 

并将其存储在名为ping.txt的文件中。然后打开该文件

//open text file ping.txt
ifstream TextFile ("ping.txt");

然后将其放入字符串向量中并显示出来。

// display ping results
for (int i=0;i<LinesFromtextFile.size(); i++){
   cout<<""<< LinesFromtextFile[i] <<"";
}

通过存储在vector<string> LinesFromtextFile中的ping内容,您可以自由地对其进行操作。

#include <windows.h>
#include <iostream>
#include <vector>
#include <string>
#include <fstream>       
using namespace std;


int main () {

    int j=0;
    char *url = new char[256];
    string line;
    vector<string> LinesFromtextFile;

    memset(url,' ', sizeof(url) );
    strcpy(url, "ping www.google.com > ping.txt " );

    cout<<"\n\n"<< url <<"\n\n";

    // launch ping from visual c++
    system( url );

    //open text file ping.txt
    ifstream TextFile ("ping.txt");
    while (getline(TextFile, line)){

        // store lines from textfile into vector
        LinesFromtextFile.push_back(line);
        LinesFromtextFile[j] = LinesFromtextFile[j] +"\n";

        j++;
    }
    TextFile.close();

    // display ping results
    for (int i=0;i<LinesFromtextFile.size(); i++){
       cout<<""<< LinesFromtextFile[i] <<"";
    }
    delete[] url;


cout<<"\nPress ANY key to close.\n\n";
cin.ignore(); cin.get();
return 0;
} 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接