【问题标题】:Need to skip newline char (\n) from input file需要从输入文件中跳过换行符 (\n)
【发布时间】:2011-02-03 04:29:02
【问题描述】:

我正在将一个文件读入一个数组。它正在读取每个字符,问题在于它还读取文本文件中的换行符。

这是一个数独板,这是我在字符中读取的代码:

bool loadBoard(Square board[BOARD_SIZE][BOARD_SIZE])
{
  ifstream ins;

  if(openFile(ins)){

    char c;

    while(!ins.eof()){
      for (int index1 = 0; index1 < BOARD_SIZE; index1++)
        for (int index2 = 0; index2 < BOARD_SIZE; index2++){ 
          c=ins.get();

          if(isdigit(c)){
            board[index1][index2].number=(int)(c-'0');
            board[index1][index2].permanent=true;
          }
        }
    }

    return true;
  }

  return false;
}

就像我说的,它读取文件,显示在屏幕上,只是遇到\n时顺序不正确

【问题讨论】:

  • 如果是作业问题,请将问题标记为作业。

标签: c++ newline sudoku


【解决方案1】:

你可以把你的 ins.get() 放在一个 do while 循环中:

do { 
    c=ins.get();
} while(c=='\n');

【讨论】:

    【解决方案2】:

    在您的文件格式中,您可以简单地不保存换行符,或者您可以添加一个 ins.get() for 循环。

    你也可以将你的 c=ins.get() 包装在一个类似 getNextChar() 的函数中,它会跳过任何换行符。

    我想你想要这样的东西:

     for (int index1 = 0; index1 < BOARD_SIZE; index1++)
     {
      for (int index2 = 0; index2 < BOARD_SIZE; index2++){
    
       //I will leave the implementation of getNextDigit() to you
       //You would return 0 from that function if you have an end of file
       //You would skip over any whitespace and non digit char.
       c=getNextDigit();
       if(c == 0)
         return false;
    
       board[index1][index2].number=(int)(c-'0');
       board[index1][index2].permanent=true;
      }
     }
     return true;
    

    【讨论】:

    • 你能说得更具体一点吗?这里几乎是一个n00b。也许我没有很好地解释自己 - 我需要它在遇到换行时跳过它而不是将它写入数组的元素......
    • @igor:是的,我会的,但我首先有一个问题,文件在每一行之后是否有换行符?
    • 是的,但我想(因为这将被发送到“自动评分器”)换行符可以在任何地方?但是可以肯定的是,让我们继续这样的概念,即换行符仅在每一行之后..
    • @igor:我会把 getNextDigit() 的实现留给你
    • 谢谢大家,这有帮助。 (但我也发现这不是问题所在,哈哈)但我也学到了更多。谢谢。
    【解决方案3】:

    您有几个不错的选择。不要在文件中保存换行符,在循环中明确丢弃它们,或者在&lt;string&gt; 中使用std::getline()

    例如,使用getline():

    #include <string>
    #include <algorithm>
    #include <functional>
    #include <cctype>
    
    using namespace std;
    
    // ...
    
    string line;
    for (int index1 = 0; index1 < BOARD_SIZE; index1++) {
        getline(is, line); // where is is your input stream, e.g. a file
        if( line.length() != BOARD_SIZE )
            throw BabyTearsForMommy();
        typedef string::iterator striter;
        striter badpos = find_if(line.begin(), line.end(),
                                 not1(ptr_fun<int,int>(isdigit)));
        if( badpos == line.end() )
            copy(board[index1], board[index1]+BOARD_SIZE, line.begin());
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-05
      相关资源
      最近更新 更多