简体   繁体   English

如何停止用换行符输入

[英]How can I stop input with newline character

I am reading a list of numbers separated by spaces. 我正在阅读用空格分隔的数字列表。 Currently the loop stops when I press Ctrl + Z. I just need to know how to modify the loop to terminate when I hit enter or if it meets the newline('\\n') character. 目前,当我按Ctrl + Z时,循环停止。我只需要知道如何修改循环以在按Enter或遇到换行符('\\ n')时终止。

    int numArrayCount = 0;
    int num, count = 0;
    int binaryArray[CAPACITY];
    int numArray[CAPACITY];  

    //takes in positive numbers higher than zero and less than 64. 
    //End output with Ctrl+Z

    while (scanf_s( "%d", &num ) == 1) {
        if (num < 64 && num > 0) {
            binaryArray[ count++ ] = base10ToBinary(num);
            numArray[ numArrayCount++ ] = num;
        }
    }

There is no direct way, because scanf and friends are only a poor man's parser . 没有直接的方法,因为scanf和朋友只是穷人的解析器 As long as you have values separated with an arbitrary number of space characters (space, tab, return, linefeed and vtab) and it does not matter what those separators are, scanf is fine. 只要您使用任意数量的空格字符(空格,制表符,返回符,换行符和vtab)分隔值,并且这些分隔符是什么无关紧要, scanf就可以了。

If you want to process lines, and then can parse the content of a line, fgets is the way to go. 如果要处理行,然后可以解析行的内容,则可以使用fgets Unfortunately, you cannot repeatedly scan from a string, but you can build nice string parsers with strtok or better strcspn 不幸的是,您不能从字符串中反复扫描,但是可以使用strtok或更好的strcspn构建漂亮的字符串解析器。

Other languages (C++, Java, etc.) or maybe other libraries may have smarter tools. 其他语言(C ++,Java等)或其他库可能具有更智能的工具。 But C was initially build as a low level language... 但是C最初是作为低级语言构建的...

How can I stop input with newline character (?) 如何停止以换行符(?)输入

Look for the '\\n' with getchar() before scanf( "%d", &num ) as "%d" quietly consumes leading white-space including '\\n' . scanf( "%d", &num ) getchar()之前用getchar()查找'\\n' ,因为"%d"悄悄地占用了包括'\\n'前导空格。

// concept code
int ch;
while (isspace(c = getchar())) {
  if (c == '\n') return "We are done, \\n"
}
if (c == EOF) return "We are done, EOF"
// put back
ungetc(c, stdin);
if (scanf( "%d", &num ) != 1) return "Non-numeric input";
return "Success";

Full solution here for float . 完整的解决方案在这里 float


An alternative approach uses fgets() and then pares the string . 另一种方法是使用fgets()然后解析string This good approach does has trouble with long line management and fails should the line of input include an uncommon null character . 这种好方法在长行管理方面确实存在麻烦,并且如果输入包含不常见的空字符,则该方法将失败。

while (scanf_s(" %d", &num) == 1) {

Insert a space before the %d as it will make the scanf function disregard the input that was leftover from whatever was left in stdin and you won't need that getchar() anymore. %d之前插入一个空格,因为它将使scanf函数无视stdin中剩下的任何输入,而您将不再需要该getchar()。

在此处输入图片说明

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

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