C++ cout cin 字符串操作

发布于 2024-08-11 08:20:19 字数 813 浏览 3 评论 0原文

我正在尝试从命令行获取一行作为输入。我的问题是我没有得到整条线,但它被空间标记化了。

因此,如果我输入诸如“我非常喜欢数学”之类的内容而不是得到

"you enterend: I like Math a lot"

以下内容:

EDITING MODE: Enter a command
i like Math a lot
you entered i

EDITING MODE: Enter a command
you entered like

EDITING MODE: Enter a command
you entered Math

EDITING MODE: Enter a command
you entered a

EDITING MODE: Enter a command
you entered lot


void enterEditingMode(){
    editingMode = TRUE;
    static string CMD = "\nEDITING MODE: Enter a command\n";
    string input;
    while(editingMode == TRUE){
        cout << CMD;
        cin >> input;
        //we assume input is always correct
        // here we need to parse the instruction
        cout << "you entered " << input <<endl;

I'm trying to get a line as input from the command line. My problem is that I'm not getting the whole line, but it's being tokenized by space.

So if I entered something such as "I like Math a lot" instead of getting

"you enterend: I like Math a lot"

I get the follwoing:

EDITING MODE: Enter a command
i like Math a lot
you entered i

EDITING MODE: Enter a command
you entered like

EDITING MODE: Enter a command
you entered Math

EDITING MODE: Enter a command
you entered a

EDITING MODE: Enter a command
you entered lot


void enterEditingMode(){
    editingMode = TRUE;
    static string CMD = "\nEDITING MODE: Enter a command\n";
    string input;
    while(editingMode == TRUE){
        cout << CMD;
        cin >> input;
        //we assume input is always correct
        // here we need to parse the instruction
        cout << "you entered " << input <<endl;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

得不到的就毁灭 2024-08-18 08:20:19

std::getline 是一次读取一行输入的标准方法。

您可以这样使用它:

std::getline(std::cin, string);

它返回对输入流的引用,该引用具有到 void* 的隐式转换,因此您可以像这样轻松检查是否成功:

if (std::getline(std::cin, string))
{
    // successfully read a line...
}

std::getline is the standard way to read a line of input at a time.

You can use it like this:

std::getline(std::cin, string);

It returns a reference to the input stream which has an implicit conversion to void* so you can check for success easily like this:

if (std::getline(std::cin, string))
{
    // successfully read a line...
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文