需要从输入文件中跳过换行符 (\n)
我正在将文件读入数组。它正在读取每个字符,出现的问题是它还读取文本文件中的换行符。
这是一个数独板,这是我读取字符的代码:
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 时顺序不正确
I am reading in a file into an array. It is reading each char, the problem arises in that it also reads a newline in the text file.
This is a sudoku board, here is my code for reading in the char:
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;
}
like i said, it reads the file, displays on screen, just not in correct order when it encounters the \n
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以将 ins.get() 放入 do while 循环中:
You can put you ins.get() in a do while loop:
那么在您的文件格式中,您可以简单地不保存换行符,或者您可以添加一个 ins.get() for 循环。
您还可以将 c=ins.get() 包装在类似 getNextChar() 的函数中,该函数将跳过任何换行符。
我想你想要这样的东西:
Well in your file format you can simply not save newlines, or you can add a ins.get() the for loop.
You could also wrap your c=ins.get() in a function something like getNextChar() which will skip over any newlines.
I think you want something like this:
您有一些不错的选择。要么不要将换行符保存在文件中,在循环中显式丢弃它们,要么使用 <
中的 code>std::getline()。例如,使用 getline():
You have a few good options. Either don't save the newline in the file, explicitly discard them in your loop, or use
std::getline()
in<string>
.For example, using
getline()
: