【问题标题】:How to select parts of sentences in strings (C++)如何在字符串中选择部分句子(C++)
【发布时间】:2018-04-15 16:56:17
【问题描述】:

我正在制作一个命令行程序,我想知道如何获取句子的不同部分,所以假设有人输入 cd Windows/Cursors,它会检测(使用 if 语句)他们输入了 cd,然后(在同一个 if 语句中)它将选择句子的其余部分,并将其设置为目录。这是我的代码:

#include "stdafx.h"
#include <string>
#include <iostream>

using namespace std;
int main()
{
    while (1)
    {
        string directory = "C:/";
        string promptInput;
        string afterPrint;
        string prompt = "| " + directory + " |> ";
        cout << prompt;
        cin >> promptInput;

        if (promptInput == "") 
        {

        }
        else if (promptInput == "h:/")
        {
            directory = "H:/";
        }
        if (promptInput != "") {
            cout << "    " << afterPrint << "\n";
        }
    }
    return 0;
}

我还没有尝试过任何东西,所以我愿意接受建议。

我们将不胜感激。

-迦勒辛

【问题讨论】:

标签: c++ string shell command-line command


【解决方案1】:

您可以使用std::stringstream 读取每一行并将其转换为流。然后将行分成单独的部分,根据行中的第一个单词创建一个响应。例如:

#include <sstream>
...
int main()
{
    string line;
    while(getline(cin, line))
    {
        stringstream ss(line);
        string cmd;
        if(ss >> cmd)
        {
            if(cmd == "cd")
            {
                string dir;
                if(ss >> dir)
                {
                    cout << "changedir: " << dir << "\n";
                }
            }
            else if(cmd == "c:" || cmd == "c:\\")
            {
                cout << "changedir: " << cmd << "\n";
            }
            else
            {
                cout << "error\n";
            }
        }
    }
    return 0;
}

【讨论】:

    【解决方案2】:

    通用答案取决于您的问题集,但您的示例的具体答案可能如下所示:

    else if (promptInput == "cd")
    {
         std::string directory;
         std::getline(std::cin, directory);
         ChangeDirectory(directory);
    }
    

    【讨论】:

      猜你喜欢
      • 2016-10-24
      • 2022-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-07
      相关资源
      最近更新 更多