简体   繁体   English

识别C或C ++中的空格分隔符和换行符

[英]recognizing both space delimiter and newline character in C or C++

In programming competitions, often the input given is of the form: 在编程比赛中,通常输入的形式为:

1 3 5 544
4 
2 3 22
2423 
2 

where there are multiple lines of integers delimited by a space. 其中有多行整数用空格分隔。 I've been trying to figure out how to read these input in C or C++ but could never really get it to work. 我一直在试图弄清楚如何用C或C ++读取这些输入,但是永远无法真正使它工作。 Solutions that I've found on the web either use scanf or getline (or fget) but whenever I tried, they either failed to recognize the newline character or, when I tried to use them in conjunction with a for loop, the first iteration wasn't executed. 我在网络上找到的解决方案要么使用scanf或getline(或fget),但是每当我尝试时,它们要么无法识别换行符,要么当我尝试将它们与for循环结合使用时,第一次迭代是没有执行。

How do the competitive programmers read this type of input? 有竞争力的程序员如何阅读此类输入?

Read the stream line-by-line using getline() (suggested the "getline function", which works with std::string , not the "getline method of istream"). 使用getline()逐行读取流(建议使用“ getline函数”,它与std::string ,而不是“ istream的getline方法”)。

Then to extract the numbers use std::istringstream initialized with a string read by getline() call. 然后要提取数字,请使用std::istringstream初始化,该字符串由getline()调用读取的字符串初始化。

In competentive programming - don't use C++ input at all - it's too slow and it will reflect on your times badly (especially if expected solution is in O(n) or faster). 在熟练的编程中-根本不要使用C ++输入-它太慢了,并且会严重影响您的时间(特别是如果期望的解决方案是O(n)或更快)。 Program specifications are usually created in such a way, that trivial scanf will do the job (intentionally, so you can focus on algorithm instead of reading input). 程序规范通常以这种方式创建,即琐碎的scanf可以完成这项工作(有意地,因此您可以专注于算法而不是读取输入)。 Your problem is that probably you want to parse whitespace and don't know how to do this (with scanf - you don't need to). 您的问题是,您可能想解析空白并且不知道如何执行此操作(使用scanf-您无需这样做)。 For example, let's parse multiple lines containing two integers separated by space: 例如,让我们分析包含以整数分隔的两个整数的多行:

int x, y;
while (foo) {
    scanf("%d %d", &x, &y);
}

This will work just fine, you don't need to worry about newlines at all. 这样就可以了,您根本不必担心换行符。 If you will get into situation, that scanf is too slow (it might be in competitions) - you will probably need to create your own dedicated parsing function by calling getchar and processing input byte by byte. 如果您遇到这种情况,那么scanf太慢了(可能在竞争中)-您可能需要通过调用getchar并逐字节处理输入来创建自己的专用解析函数。

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

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