I'm trying to write an echo like thing doing this
:

> echo Muffins
Muffinst
> echo two muffins
two muffins

The problem Is that the program isn't being started from command line,
The > is my programs input prompt (trying to write a very simple command line)
How would I do this?
Would it be possible with formatted input (cin>>)?
or would I have to use scanf?

Dani AI

Generated

As suggested, use std::getline so the whole typed line is captured. Keep that original string if the goal is to show exactly what the user typed while still extracting the command token. Two simple, robust ways to split "echo" from the rest are shown below: (A) use an istringstream to take the first token and then read the remainder, or (B) find the first space and substr the rest (skip extra spaces). Both preserve the original input.

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

int main() {
    std::string line;
    while (std::cout << "> ", std::getline(std::cin, line)) {
        std::string original = line;   // keep exact user input

        // Method A: istringstream -> first token + remainder
        std::istringstream iss(line);
        std::string cmd;
        iss >> cmd;                    // gets the command word
        std::string args;
        std::getline(iss, args);       // remainder (may start with spaces)
        if (!args.empty()) {
            size_t first = args.find_first_not_of(' ');
            args = (first == std::string::npos) ? std::string() : args.substr(first);
        }

        std::cout << "original: [" << original << "]\n";
        std::cout << "cmd: [" << cmd << "]\n";
        std::cout << "args: [" << args << "]\n";

        if (cmd == "echo")
            std::cout << args << '\n';
    }
    return 0;
}

Method B (not shown in full) is similar: p = line.find(' '); cmd = (p==npos)?line:line.substr(0,p); first = line.find_first_not_of(' ', p); args = (first==npos)?"":line.substr(first).

Notes: operator>> alone drops everything after the first space, so avoid it when the rest must be preserved. If shell-like quoting/escaping is required (e.g., handling "two muffins" as a single arg), add a proper tokenizer or use an existing parsing utility. Also avoid mixing operator>> and std::getline without clearing leftover newlines.

Recommended Answers

All 3 Replies

Use getline()

How wOuld I separate echo from the rest of the string (seperatre not remove I still need to see what the person is doing)?

Write a couple test programs to understand how input works.

1) use cin in a loop to read and display what is read
2) use getline() in a loop to read and display what is read
3) same with other input commands you know

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.