【问题标题】:String manipulation and ignoring part of string字符串操作和忽略字符串的一部分
【发布时间】:2015-05-12 09:03:29
【问题描述】:

我从使用 C++ 的文本文件中输入了以下内容

command1 5 #创建5个框
长度 12
insertText 这是一个盒子

如何在忽略#sign 之后的任何内容的同时读取输入内容?

例如输出应该没有#Create 5 box

command1  5
length    12
insertText THIS IS A BOX

编辑:

我尝试了以下方法:

while(getline(myfile, line))
{
    istringstream readLine(line);
    getline(readLine, command, ' ');
    getline(readLine, input, '\0');
}

...但它似乎不起作用。

【问题讨论】:

  • 你已经尝试了什么?向我们展示您写的内容,但它不起作用,我们可能会尝试提供帮助。
  • 有很多可能性,包括正则表达式、字符串拆分等。但是看看你发布的文本格式,我猜你以后需要一个更复杂的解析器......

标签: c++ string file-io


【解决方案1】:

外部的while(getline(istringsteam 很好,但之后你想将一个空格分隔的单词读入命令,然后可能是一个或多个空格分隔的输入:类似

std::string command, input;
std::vector<std::string> inputs;
if (readLine >> command && command[0] != '#')
{
    while (readLine >> input && input[0] != '#')
        inputs.push_back(input);
    // process command and inputs...
}

使用&gt;&gt;getline 解析readLine 更容易,因为如果它们没有获得至少一个有效字符,它们会设置流失败状态,从而使[0] 索引安全并干净地退出空行,或没有输入的命令。

【讨论】:

    【解决方案2】:

    您可以像这样简单地使用std::getline()

    int main()
    {
        std::ifstream ifs("file.txt");
    
        std::string line;
        while(std::getline(ifs, line))
        {
            std::istringstream iss(line);
    
            if(std::getline(iss, line, '#')) // only read up to '#'
            {
                // use line here
                std::cout << line << '\n';
            }
        }
    }
    

    输出:

    command1 5 
    length 12
    insertText THIS IS A BOX
    

    【讨论】:

      【解决方案3】:

      在您逐个检查每个字符的函数中,添加以下代码:(伪代码)

      if(currChar == #){
          while(currChar != '\n'){
              getNextChar();// you arent saving it so youre ignoring it
          }
       }else{
          Char c = getNextChar();
          //now you can add this character to your output string
      

      【讨论】:

        【解决方案4】:

        例如。你可以使用 ignore(inputSize, "#") 或者你可以使用 getline http://www.cplusplus.com/reference/istream/istream/ignore/ http://www.cplusplus.com/reference/istream/istream/getline/

        【讨论】:

          猜你喜欢
          • 2021-07-06
          • 1970-01-01
          • 2010-09-05
          • 1970-01-01
          • 2021-08-27
          • 1970-01-01
          • 1970-01-01
          • 2019-05-26
          • 1970-01-01
          相关资源
          最近更新 更多