简体   繁体   English

如何摆脱C ++中的空白行?

[英]how to get rid of blank line in c++?

I'm trying to fill text document, but when I do - I get first line blank. 我正在尝试填充文本文档,但是当我这样做时-我得到第一行空白。 My text document, I'm reading from, looks like this: 我正在阅读的文本文档如下所示:

3
first fr random 5
second          9
third shazam    2

I've tried removing first value and so blank line went away. 我尝试删除第一个值,所以空白行消失了。 So it correlates, but I need that value. 因此它具有相关性,但我需要该值。

// My code
ifstream in("U2.txt"); 
ofstream out("U2.txt");
int n;
in>>n;
char vardaiStart[n][21];

in.read(vardaiStart[0], 21);

out << vardaiStart[0]<< endl;

output looks like this: 输出看起来像这样:

*blank*
first fr random

but what I want is: 但我想要的是:

first fr random

So, in other projects I won't be using old C since now, but for this project I red that [endline] and ignored it like this: in.ignore(std::numeric_limits<std::streamsize>::max(), '\\n'); 因此,从现在开始,在其他项目中我将不再使用旧的C,但是对于该项目,我将[endline]变成红色,并按如下方式忽略它: in.ignore(std::numeric_limits<std::streamsize>::max(), '\\n');

Your input file looks like: 您的输入文件如下所示:

3[endline]
first fr random 5[endline]
second          9[endline]
third shazam    2[endline]

Note the [endline] I added: they can be '\\n', '\\r\\n' depending on the system that generated the file. 注意我添加的[endline] :它们可以是'\\n', '\\r\\n'具体取决于生成文件的系统。

Your first instruction is: 您的第一个指示是:

in >> n;

a formatted input read: you are asking to read an integer from the file, so only characters that can form valid integers will be read. 格式化输入读取:您要求从文件中读取一个整数,因此将只读取可以构成有效整数的字符。

This means that after that instruction the remaining portion of the file will be: 这意味着在该指令之后,文件的其余部分将是:

[endline]
first fr random 5[endline]
second          9[endline]
third shazam    2[endline]

The rest of your code reads raw bytes, so it will read the first [endline] as well (and print it). 您的其余代码读取原始字节,因此它将也读取第一个[endline] (并打印)。

As other suggested in the comments, you should not be using variable length arrays as they are not part of any C++ standard (but part of the C one). 正如注释中的其他建议一样,您不应使用可变长度数组,因为它们不是任何C ++标准的一部分(而是C语言标准的一部分)。 Try to use the C++ standard library instead. 尝试改用C ++ 标准库

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM