How to copy a string from cmd line?

Hi, I'm totally new to coding. I need an advice from veteran because I doing this for my part of my task.

Is there a way to read a string generated by Command Prompt (CMD)?

My task is to create a code to ping all the network and assign IP address as active and inactive through <fstream>Input/output with files perhaps.

I wanted to copy a string from cmd for example:

Reply from 192.168.0.1: bytes=32 time<1ms TTL=64 <- (This indicate active)
Reply from 192.168.0.2: Destination host unreachable <- (This indicate inactive)

If I able to copy that line, I can write a If/Else condition to separate them. If there is any easier way to improve this scenario, please do assist me. Thank you.

The code below is to ping all IP Address until 255, but I still need 1 more function which to separate Active and Inactive IP Addresses.

#include <iostream>
#include <string>
#include <sstream>

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");
}
closed account (48bpfSEw)
you could redirect console output...

http://stackoverflow.com/questions/125828/capturing-stdout-from-a-system-command-optimally

I do not understand what's
popen/ _popen...
Can anyone care to explain, and code an example for Windows base.
From that very Stack Overflow page:
It executes a command, like system(), but directs the output into a new file. A pointer to the stream is returned.

Last edited on
1
2
3
4
5
6
7
8
9
std::string execute( std::string cmd ) 
{
    std::string file_name = "result.txt" ;
    std::system( ( cmd + " > " + file_name ).c_str() ) ; // redirect output to file

    // open file for input, return string containing characters in the file
    std::ifstream file(file_name) ;
    return { std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>() } ;
}

http://rextester.com/SLYX81102
I know your wanting to code this in C but if you have the option, powershell can do this much easier.

If not I agree with JLB, redirect to a temp file and then read the results.
Topic archived. No new replies allowed.